7

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

1
  • What do you mean with $key = 2? Do you want to find a certain value or a certain key? Commented May 3, 2011 at 13:10

10 Answers 10

16

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

Sign up to request clarification or add additional context in comments.

6 Comments

I would upvote this twice if I could, loooong time since I remembered PHP had a preg_grep() function!
I'm trying preg_grep("/^\/scripts\/GMC\/PNetT\-5\.1\-SP1\/PNetT.*/", exec('ps -ef | grep GMC', $output)); but it's not finding the result when I know the result exists.... am I escaping this properly?
@Webnet, exec doesn't return the array. Use two separate statements, one to call exec and the other the call preg_grep(..., $output). Or skip preg_grep entirely and just put that regular expression in your grep command directly.
Psh - you're right, I only did that so you could see what I was executing. I'm actually passing $output to the preg_grep, but it's not matching. Is it escaped correctly?
Yes, but it's too restrictive. The ^ at the start of the expression says the substring must start some line of the program output, but that's not where ps puts the command line. Remove the ^ from the start and the .* from the end (which is redundant). Also, the - characters don't need to be escaped; they're not usually special. (Even in [...], they don't need escaping if you put them in the right place.)
|
2

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'
)

Comments

2

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.

Comments

1

There is no built-in function but since preg_* functions support arrays as arguments this should work:

$keys = preg_filter('~gr~', '$0', $array);

Comments

1

what about foreach ?

function xxxxxx($str, $array) {
  foreach ($array as $key => $value) {
     if (strpos($value, $str) !== false) {
        return $key;
     }
  }
  return false;
}

1 Comment

This method worked perfect for what I was after. I altered it slightly so I can feed single and multiple needles. function find($haystack, $needles) { $needle = array_map('trim', explode(",", $needles)); foreach ($needle as $key => $value) { if (strpos($value, $haystack) !== false) { return true; } } return false; } Then I call something like find($page, "home, about");
0

use

array_walk with strpos

array_walk

1 Comment

And the arguments to strpos go where?
0

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.

Comments

0

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);
?>

Comments

0

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; });

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.