0

I have two arrays, for example the following:

$array1 = array(3,4,3,1);

$array2 = array(2,5,3,0);

each key of the 2 arrays should now be compared and with the smaller value number of each key, I want to create a new array. In this case the new array should be this:

$result = array(2,4,3,0)   

How can I do this?

1
  • 1
    You can do this with a simple for-loop, checking both arrays in parallel Commented May 27, 2014 at 18:37

4 Answers 4

2

You can use array_map like this:

$array1 = array(3,4,3,1);    
$array2 = array(2,5,3,0);

$result = array_map(min, $array1, $array2);
print_r($result);

array_map applies a function (in this case min) to each element of an array and returns the resulting array. If more than one array is passed to array_map, the corresponding elements from each array are used as arguments to the function.

Output:

Array ( [0] => 2 [1] => 4 [2] => 3 [3] => 0 )
Sign up to request clarification or add additional context in comments.

Comments

2

array_map is your friend:

$array1 = array(3,4,3,1);
$array2 = array(2,5,3,0);

$array3 = array_map(min,$array1,$array2);

print_r($array3);

gives:

Array
(
    [0] => 2
    [1] => 4
    [2] => 3
    [3] => 0
)

Comments

0

Don't know if array_push is the most elegant solution, but the result seems to be what you're looking for.

$array1 = array(3,4,3,1);
$array2 = array(2,5,3,0);
$result = array();
$len = count($array1);

for($i = 0; $i < $len; $i++) {
    $array1[$i] < $array2[$i] ? array_push($result, $array1[$i]) : array_push($result,            $array2[$i]);
}
print_r($result);

Result:

Array
(
    [0] => 2
    [1] => 4
    [2] => 3
    [3] => 0
)

Comments

0

You can use this as a concept

$array3 = array(); 
for($a = 0; a < count($array1); $a++)
{
    if($array1[$a]<$array2[$a])
        $array3[$a]=$array1[$a];
    else
        $array3[$a]=$array2[$a];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.