AJK
AJK

Reputation: 87

Why does max(array_push()) not find max?

Up front, I would like to clarify that I am not looking for a workaround to find max--I already have the solution for accomplishing that goal. What I am curious about is why max(array_push()) doesn't work.

I have an array with many values in it, and want to find the max of specific values within that array. Existing array:

$array1 = array(2,6,1,'blue','desk chair');

The basic idea is to create a new array consisting of those specified values, and then find the max of that new array. I attempted to make this effort operate all on one line:

$max = max(array_push($array2, $array1[0], $array1[1], $array1[2]));
//this doesn't work at all, since $array2 doesn't already exist, as per the PHP manual

I changed to code to first create $array2, but didn't assign values at that time, just to see if the code works.

$array2 = array();
$max = max(array_push($array2, $array1[0], $array1[1], $array1[2]));
//$array2 is populated, but $max is not assigned

The obvious solution is to assign values to $array2 at creation and then use max() by itself. I'm just curious as to why max(array_push()) doesn't find max, since compounded functions normally operate from inside to outside.

Thank you.

Upvotes: 0

Views: 169

Answers (2)

localheinz
localheinz

Reputation: 9582

You could also use array_slice():

$max = max(array_slice(
    $array1,
    0,
    3
));

if

  • the values you are interested in are in a sequence
  • you know offset and length of the sequence

For reference, see:

For an example, see:

Upvotes: 0

apokryfos
apokryfos

Reputation: 40681

max needs an array to work with but array_push returns an integer and actually uses the provided array by reference, you have to do :

$array2 = array();
array_push($array2, $array1[0], $array1[1], $array1[2])
$max = max($array2);

Alternatively do:

$array2 = array($array1[0], $array1[1], $array1[2]);
$max = max($array2);

A 3rd option (though not the cleanest one):

$array2 = array();
$max = max($array2 = array_merge($array2, [$array1[0], $array1[1], $array1[2]]));

For reference, see:

Upvotes: 1

Related Questions