# 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

#### 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

#### 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

#### 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;

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