50
$example = array('An example','Another example','Last example');

How can I do a loose search for the word "Last" in the above array?

echo array_search('Last example',$example);

The code above will only echo the value's key if the needle matches everything in the value exactly, which is what I don't want. I want something like this:

echo array_search('Last',$example);

And I want the value's key to echo if the value contains the word "Last".

1
  • 4
    Loop over the array, use your favorite string comparison method, remember the key... Commented Sep 7, 2012 at 9:39

7 Answers 7

74

To find values that match your search criteria, you can use array_filter function:

$example = array('An example','Another example','Last example');
$searchword = 'last';
$matches = array_filter($example, function($var) use ($searchword) { return preg_match("/\b$searchword\b/i", $var); });

Now $matches array will contain only elements from your original array that contain word last (case-insensitive).

If you need to find keys of the values that match the criteria, then you need to loop over the array:

$example = array('An example','Another example','One Example','Last example');
$searchword = 'last';
$matches = array();
foreach($example as $k=>$v) {
    if(preg_match("/\b$searchword\b/i", $v)) {
        $matches[$k] = $v;
    }
}

Now array $matches contains key-value pairs from the original array where values contain (case- insensitive) word last.

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

10 Comments

if you are not trying to find by a regex don't forget to add preg_quote() to $searchword.
Actually, this gives a syntax error, unknown where and it does not work... when I comment this like $matches = array_filter($example, function($var) use ($searchword) { return preg_match("/\b$searchword\b/i", $var); }); the script continues to work, when i add it it breaks.
@LachezarRaychev What version of php are you using? It works in 5.4, 5.5 and 5.6.
Nothing technically wrong with this but I can't for the life of me understand why use regex here wouldn't strpos() work just as well and be faster?
@billynoah Yes, it would :)
|
24
function customSearch($keyword, $arrayToSearch){
    foreach($arrayToSearch as $key => $arrayItem){
        if( stristr( $arrayItem, $keyword ) ){
            return $key;
        }
    }
}

5 Comments

@MarcioSimao This will only return the key of the first matching element, not the array of keys of all matches.
@AleksG, This is exactly what i was looking for. If i'm not mistaken, the question is about the same thing. The last user's phrase is "And I want the value's key to echo if the value contains the word "Last""
@MarcioSimao Possibly it solves the issue for you, however it's limited to a single match. If you have multiple values with word last in them, you'll only find the first one with this code.
@AleksG, Thanks to advice! But in my case, i need to find the first key, so this code is more optimized and legible.
The php manual states that strstr() and stristr() should not be used to check the existence of a substring -- for efficiency reasons.
14
$input= array('An example','Another example','Last example');
$needle = 'Last';
$ret = array_keys(array_filter($input, function($var) use ($needle){
    return strpos($var, $needle) !== false;
}));

This will give you all the keys whose value contain the needle.

Comments

3

It finds an element's key with first match:

echo key(preg_grep('/\b$searchword\b/i', $example));

And if you need all keys use foreach:

foreach (preg_grep('/\b$searchword\b/i', $example) as $key => $value) {
  echo $key;
}

2 Comments

Or even array_keys(preg_grep('/\b$searchword\b/i', $example)). I needed the same functionality and was going to write a wrapper function as well but this is perfect.
When adding a variable into a pattern, we should see preg_quote().
0

The answer that Aleks G has given is not accurate enough.

$example = array('An example','Another example','One Example','Last example');
$searchword = 'last';
$matches = array();
foreach($example as $k=>$v) {
    if(preg_match("/\b$searchword\b/i", $v)) {
        $matches[$k] = $v;
    }
}

The line

if(preg_match("/\b$searchword\b/i", $v)) {

should be replaced by these ones

$match_result = preg_match("/\b$searchword\b/i", $v);
if( $match_result!== false && $match_result === 1 ) {

Or more simply

if( preg_match("/\b$searchword\b/i", $v) === 1 ) {

In agreement with http://php.net/manual/en/function.preg-match.php

preg_match() returns 1 if the pattern matches given subject, 0 if it does not, or FALSE if an error occurred.

1 Comment

When adding a variable into a pattern, we should see preg_quote(). preg_match() used as a filter in a loop is more elegantly expressed as preg_grep().
0

I do not like regex because as far as I know, they are always slower than a normal string function. So my solution is:

function substr_in_array($needle, array $haystack)
{
    foreach($haystack as $value)
    {
        if(strpos($value, $needle) !== FALSE) return TRUE;
    }
    return FALSE;
}

1 Comment

This does not return the key as desired (and demonstrated elsewhere).
-1

I was also looking for a solution to OP's problem and I stumbled upon this question via Google. However, none of these answers did it for me so I came up with something a little different that works well.

$arr = array("YD-100 BLACK", "YD-100 GREEN", "YD-100 RED", "YJ-100 BLACK");
//split model number from color
$model = explode(" ",$arr[0])
//find all values that match the model number
$match_values = array_filter($arr, function($val,$key) use (&$model) { return stristr($val, $model[0]);}, ARRAY_FILTER_USE_BOTH);
//returns
//[0] => YD-100 BLACK
//[1] => YD-100 GREEN
//[2] => YD-100 RED

This will only work with PHP 5.6.0 and above.

4 Comments

This is a departure from the OP's question / sample data / requirements.
@mickmackusa this appeared first on Google when looking for a solution and since none of the aforementioned solutions helped me, I had to come up with my own solution. I posted it so others looking for a solution could benefit from it.
When you have a new question which is not solved by a pre-existing page, ask a new question then self-answer it. This way question deviation is avoided. Answers posted on a given page are expected to solve the OP's question, but your answer ignores the OP's question.
Furthermore, ARRAY_FILTER_USE_BOTH is useless here and the php manual advises against the use of strstr() as a means to check if a substring exists. strstr($arr[0], ' ', true) should grab the leading substring. There is no reason to make the leading substring modifiable by reference because you never modify it.

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.