I need to find out if a string exists within an array value, but isn't necessarily the actual array value.
$array = array(
0 => 'blue',
1 => 'red',
2 => 'green',
3 => 'red'
);
$key = xxxxxx('gr', $array); // $key = 2;
Is there a built in way to do this with PHP
You can use preg_grep for this purpose
<?php
$array = array(
0 => 'blue',
1 => 'red',
2 => 'green',
3 => 'red'
);
//$key = xxxxxx('gr', $array); // $key = 2;
$result=preg_grep("/^gr.*/", $array);
print_r($result);
?>
DEMO
Function: array_filter is what you want. It will only preserve the items in the resulting array when the specified function return true for them.
// return true if "gr" found in $elem
// for this value
function isGr($key, $elem)
{
if (strpos($elem, "gr") === FALSE)
{
return FALSE;
}
else
{
return TRUE;
}
}
$grElems = array_filter($array, "isGr");
print_r($grElems);
results in:
array(
2=>'green'
)
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