php - How to get common minimum value in two arrays

420

I have a function where is checks on two arrays and returns the common minimum value in both the arrays. IT returns the correct answer when both the arrays have equal number of elements. But is the other other is bigger it does not return the correct one. How to overcome this?

<?php
    $A = array(0);
    $B= array(1,0);
    $n = sizeof($A);
    $m = sizeof($B);
    sort($A);
    sort($B);
    $i = 0;
    for ($k = 0; $k < $n; $k++) {
        if ($i < $m - 1 AND $B[$i] < $A[$k])
            $i += 1;
        if ($A[$k] == $B[$i])
            echo $A[$k];
    }
    echo "end";

?>

Thanks

900

Answer

Solution:

A way simpler way would be to take the minimum value of the intersection of your arrays :

$array = array (5,6,7,8,9);
$array2 = array (9,7,5,3,4,1);

$min = min(array_intersect($array, $array2));
echo $min; // 5
621

Answer

Solution:

Leverage PHP function array_intersect() to extract common values in two arrays, then fetch the minumum value by using min()

Like so:

<?php

$arrayOne = [1, 3, 5, 6, 7];
$arrayTwo = [0, 9, 2, 3, 4, 5];

echo min(array_intersect($arrayOne, $arrayTwo)); // 3
159

Answer

Solution:

I would use array_intersect. It will give you an array with only values that are present in both arrays you are looking through, then you can find the lowest value in the array

$A = array(0,5,4,3,2,1,4);
$B = array(0,1,3,4);
$C = array_intersect($A, $B);
$low = $C[0];

for($i = 0; $i < count($C); $i++) {
   if($C[$i] < $low) 
      $low = $C[$i];
}

echo "Lowest shared number is $low";

People are also looking for solutions to the problem: php - Best way to deploy from git

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.