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
<?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();
?>
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.
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...
function smallest_common_number(){
global $a, $b, $c;
echo min(array_intersect($a, $b, $c));
}
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Find the answer in similar questions on our website.
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.
PHP (from the English Hypertext Preprocessor - hypertext preprocessor) is a scripting programming language for developing web applications. Supported by most hosting providers, it is one of the most popular tools for creating dynamic websites.
The PHP scripting language has gained wide popularity due to its processing speed, simplicity, cross-platform, functionality and distribution of source codes under its own license.
https://www.php.net/
Welcome to the Q&A site for web developers. Here you can ask a question about the problem you are facing and get answers from other experts. We have created a user-friendly interface so that you can quickly and free of charge ask a question about a web programming problem. We also invite other experts to join our community and help other members who ask questions. In addition, you can use our search for questions with a solution.
Ask about the real problem you are facing. Describe in detail what you are doing and what you want to achieve.
Our goal is to create a strong community in which everyone will support each other. If you find a question and know the answer to it, help others with your knowledge.