Search code examples
phparrayscomparisonmax

How to get max element at each index while comparing two arrays?


I have two indexed arrays of identical length:

$first_array = [1,3,4,5,6]; 
$second_array = [5,2,1,7,9];

I need to generate a new array that consists of the higher value between the two elements at each index.

The output should be:

$output_array[5, 3, 4, 7, 9];

Solution

  • Super easy one-liner:

    Pass both arrays to array_map(), as it synchronously loops through both sets of data, call max() on the two elements.

    Code: (Demo)

    $first_array = [1, 3, 4, 5, 6];
    $second_array = [5, 2, 1, 7, 9];
    
    var_export(array_map('max', $first_array, $second_array));
    

    Output:

    array (
      0 => 5,
      1 => 3,
      2 => 4,
      3 => 7,
      4 => 9,
    )