I need to find the key and the value from an array that contains a specific letter without using the loop.
for Eg
$animal= array('lion','elephant','tiger');
I need to fetch the key and value which contain 'io'
output :
0 - lion
I need to find the key and the value from an array that contains a specific letter without using the loop.
for Eg
$animal= array('lion','elephant','tiger');
I need to fetch the key and value which contain 'io'
output :
0 - lion
use array_walk function. this function will apply user-defined callback function to each element of the array
$animal= ['lion','elephant','tiger','lions'];
array_walk($animal, function($value, $key) use (&$array)
{
if(strpos($value,'io') !== false)
$array[$key]= $value;
});
var_dump($array);
it give output:
Array (
[0] => lion
[3] => lions )
You can use array_filter
with option ARRAY_FILTER_USE_BOTH
$animal = array('lion','elephant','tiger');
$search = 'io';
$res = array_filter($animal, function($v, $k) use($search){
return strpos($v, $search);
}, ARRAY_FILTER_USE_BOTH);
echo '<pre>';
print_r($res);
Working example :- https://3v4l.org/bdDSF
loop over array with foreach
and use a test strpos($value, $search) !== false
, Which means $search
exist in $value
, So take position of it which is $key
with its value, store them in $array
. or just show them immediately (uncomment the echo line).
$animal = array('lion','elephant','tiger','ions');
$array = [];
$search = 'io';
foreach ($animal as $key => $value) {
if(strpos($value, $search) !== false){
$array[$key] = $value;
//echo $key." - ".$value."<br>";
}
}
Results:
foreach ($array as $key => $value) {
echo $key." - ".$value."<br>";
}
Output:
/*
0 - lion
3 - ions
*/