0

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

msanford
  • 11,803
  • 11
  • 66
  • 93
Pradeep
  • 51
  • 1
  • 3
  • 9
  • 1
    This looks very C-styled, which is going to cause you problems in PHP. We have `foreach` loops that will improve the readability of this. Also we have `count` as opposed to `sizeof` for arrays. – Muhammad Abdul-Rahim Apr 14 '15 at 19:15
  • 1
    use PHP functions `array_intersect` and `min` – Ejaz Apr 14 '15 at 19:16
  • What's wrong with something simple like `$minimumCommonValue = min(array_intersect($A, $B));`... aside from the error handling if there's no common values – Mark Baker Apr 14 '15 at 19:17
  • I might suggest getting into the habit of using `&&` instead of `AND`; it is not a purely stylistic choice: http://stackoverflow.com/questions/2803321/and-vs-as-operator – msanford Apr 14 '15 at 19:19

3 Answers3

6

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
Clément Malet
  • 5,062
  • 3
  • 29
  • 48
0

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
0

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";
leitning
  • 1,081
  • 1
  • 6
  • 10