I have an array and I'd like to search for the string 'green'
. So in this case it should return the $arr[2]
$arr = array(0 => 'blue', 1 => 'red', 2 => 'green string', 3 => 'red');
is there any predefined function like in_array() that does the job rather than looping through it and compare each values?
For a partial match you can iterate the array and use a string search function like strpos().
function array_search_partial($arr, $keyword) { foreach($arr as $index => $string) { if (strpos($string, $keyword) !== FALSE) return $index; } }
For an exact match, use in_array()
in_array('green', $arr)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With