PHP provide a lots of built in functions for manipulation of array. in_array is one of the useful built in function of PHP which is used to check whether a specified value exists in array or not. If the search value found in array the function returns TRUE, otherwise FALSE.
Syntax : in_array(value, array, mode)
Description :
value : Specifies the value to be search in array.(Required)
array : The array to be search.(Required)
mode : If set to true, function also checks the type of value in array.(Optional)
Example :
<?php
$arr = array(17, "Apple", '14', 27.21);
echo in_array(14, $arr) ? 'Match' : 'Not Match';
echo "<br>";
echo in_array(14, $arr, TRUE) ? 'Match' : 'Not Match';
?>
Output :
Match
Not Match
In the above example we used in_array() with one dimension array. With multi-dimensional array in_array() not work properly. Below is the script which is used to check existence of value in multidimensional array.
Check value exist in multidimensional array
function multidim_in_array($search_value, $array) {
foreach ($array as $val) {
if ( ($val === $search_value) ){
return true;
}elseif(is_array($val)){
$status = multidim_in_array($search_value, $val);
if($status == true)
return true;
}
}
return false;
}
In the above script we pass the search value (the value which is to be search in array) and array(in which value has to be search) as parameters in function multidim_in_array(). Firstly the function used a foreach loop to check each value of passed array. If the array value matched with the search value, function returns true. If array value is an array(in case of multi-dimensional array), multidim_in_array() called recursively. If search string matched with values in array, function returns true otherwise return false.
Example :
<?php
$records = array
(
array("Amit",32,68),
array("Ankit",25,45),
array("Rahul",28,28),
array("Ravi",42,36)
);
if(multidim_in_array("Rahul", $records)){
echo "Value exist in array";
}else{
echo "Value not exist";
}
?>
Output : Value exist in array
0 Comment(s)