I am trying to create a function that will output the smallest common int or return false if there is not one in three arrays. The arrays are sorted ascending and I want to do with array_search.
When I execute this code it returns nothing and I don’t know why it should echo 5 I think
JavaScript
x
<?php
$a=array(1,2,3,5,6);
$b=array(2,3,4,5,6);
$c=array(4,5,6,7,8);
$arrlength = count($a);
function smallest_common_number(){
global $a, $b, $c;
foreach ($a as $value) {
$x=array_search($a[0], $b);
array_search($x,$c);
echo $x
}
}
smallest_common_number();
?>
Advertisement
Answer
Here is a different method of doing it.
First I find the lowest number that it could possibly be $min.
Then I loop the $a array and skip until I find at least $min.
if array search of $b and $c is not false then we found the lowest possible match and break the code.
JavaScript
function smallest_common_number(){
global $a, $b, $c;
$min = max(min($a), min($b), min($c));
foreach ($a as $value) {
if($value >= $min){
if(array_search($value, $b) !== false && array_search($value, $c) !== false){
echo $value;
break;
}
}
}
}
But the simplest code is probably array_intersect. But OP asked for array_search…
JavaScript
function smallest_common_number(){
global $a, $b, $c;
echo min(array_intersect($a, $b, $c));
}