PHP in_array function use and examples
This
short article how to use PHP in_array function with arrays. See the
description with usage details and reusable code examples below. The
details of how to use in_array with normal or multidimensional arrays is
also included.
Step 1 - PHP in_array function usage examples
PHP in_array function use and examples
bool in_array ( mixed $what , array $where [, bool $strict = FALSE ] )
By default you simply use only the 2 mandatory parameters ($what and $where) as you can see in the following example:
Code:
$myArray = array("Audi","BMW","Lexus","Mercedes");
var_dump($myArray);
if (in_array("Lexus", $myArray)) {
echo "Lexus was found in the array<br/>";
}
if (in_array("opel", $myArray)) {
echo "Opel was found in the array<br/>";
}
If you want to force th in_array function to check also variable types then, you need to set the optional strict parameter to true as you can see in the next code example:
Code:
$myArray = array(10,20,30,40,50);
var_dump($myArray);
if (in_array("10", $myArray)) {
echo "A - 10 was found as string in the array without strict<br/>";
}
if (in_array("10", $myArray, TRUE)) {
echo "B - 10 was found as string in the array using strict<br/>";
}
The in_array function only checks the values in the array and so if you want to check the keys in case of an associative array then you need to use the array_key_exists function as demonstrated below:
Code:
$myArray = array("Audi"=>"A4","Audi"=>"A6","Lexus"=>"IS","Lexus"=>"LS");
var_dump($myArray);
if (in_array("Lexus", $myArray)) {
echo "Lexus was found in the array<br/>";
}
if (array_key_exists("Lexus", $myArray)) {
echo "Lexus key was found in the array<br/>";
}
The next general question is how to find a value in a multidimensional array. Unfortunately in_array is not able to handle multidimensional arrays so you need to create your own function to solve this problem. However with a simple recursive function you can do this as you can see in the next example code:
Code:
function in_array_multi($needle, $haystack) {
foreach ($haystack as $item) {
if ($item === $needle || (is_array($item) && in_array_multi($needle, $item))) {
return true;
}
}
return false;
}
$myArray = array(array(10,20),array(11,22),array(111,222));
var_dump($myArray);
if (in_array(11, $myArray)) {
echo "11 was found";
}
if (in_array_multi(11, $myArray)) {
echo "11 was found with multi";
}
0 comments:
Post a Comment