Y
Y
Yastr2018-03-16 21:26:06
PHP
Yastr, 2018-03-16 21:26:06

How to get minimum price from php array?

There is an array:

Array ( [0] => 64 654 руб. [1] => 231 654 руб. [2] => 9 879 руб. [3] => 164 руб. [4] => 2 815 руб. )

There is a task:
Get the minimum price while maintaining all spaces and currency designations.
Now I do this:
I bring the values ​​​​to a prime number and choose the smallest one, but spaces are lost, etc.
Please tell me how to do this correctly.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
direx, 2018-03-16
@Yastr

<?php

$numbers = [
    '64 654 руб.',
    '231 654 руб.',
    '9 879 руб.',
    '164 руб.',
    '2 815 руб.'
];

var_dump(
    getMinNumberFromArray($numbers, true), // float(164)
    getMinNumberFromArray($numbers) // string(11) "164 руб.",
);

/**
 * Поиск минимального числа в массиве
 * @param array $numbers
 * @param boolean $format
 * @return string|flaot|null
 */
function getMinNumberFromArray(array $numbers, $format = false)
{
    $minIndex = null;
    $minNum = null;

    foreach ($numbers as $k => $number) {
        $number = (float)preg_replace("/[^0-9,.-]/", "", $number);

        if (is_null($minNum) || $number < $minNum) {
            $minIndex = $k;
            $minNum = $number;
        }
    }

    if(is_null($minNum)){
        return null;
    }

    return ($format) ? $minNum : $numbers[$minIndex];
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question