Running "strpos" on each array element
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 =&g开发者_运维知识库t; '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'
)
Your xxxxxx
would be array_map
. But alas, you cannot use strpos
as plain callback here. To pass the actual search parameter, you need to define a custom or anonymous function-
And to get what you want, you need more wrapping still:
$key = key(
array_filter(
array_map(
function($s){return strpos($s, "gr");},
$array
),
"is_int")
);
This gives you the searched index 2
however.
There is no built-in function but since preg_*
functions support arrays as arguments this should work:
$keys = preg_filter('~gr~', '$0', $array);
what about foreach ?
function xxxxxx($str, $array) {
foreach ($array as $key => $value) {
if (strpos($value, $str) !== false) {
return $key;
}
}
return false;
}
use
array_walk with strpos
array_walk
Loop through the array and check each item, then return the index if it does.
function substr_in_array($array, $substr) {
foreach ($array as $index => $item) {
if (strrpos($item, $substr)!===FALSE && $item != $substr) {
return $index;
}
}
}
This should do what you want.
It checks using foreach every array element using strpos.
<?php
$array = array(
0 => 'blue',
1 => 'red',
2 => 'green',
3 => 'red'
);
$search='aaa';
function arraysearch($array,$search){
foreach ($array as $element){
if(strpos($element,$search)!==FALSE){
return TRUE;
}
}
return FALSE;
}
echo arraysearch($array,$search);
?>
With PHP 5.3 you can do it in one command using array_filter and an anonymous function:
$keys = array_filter($array, function($var){ return strpos($var, 'gr') !== false; });
By using PHP >= 5.3.0, you could use anonymous functions as callback to filter that array with array_filter.
$array = array(
0 => 'blue',
1 => 'red',
2 => 'green',
3 => 'red'
);
$search = 'gr';
$key = array_filter($array, function($element) use($search) {
return strpos($element,$search) !== FALSE;
});
This is an improved version of Shay Ben Moshe
response.
精彩评论