3

I have an array which contains some elements with two words, for example array("Dark Blue", "Carnation Pink").. What function do I need to use to search an array value that contains a specified string to be search. If I searched "Dark", the value "Dark Blue" should show.

2 Answers 2

1

You could use preg_grep().

$found = preg_grep('/\bDark\b/', $arr);

CodePad.

You could also use array_filter() and preg_match() with a regex..

$found = array_filter($arr, function($value) {
  return preg_match('/\bDark\b/', $value);
});

CodePad.

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

Comments

0

Maybe a good old fashioned foreach loop?

$search_for = "Dark";

foreach (array("Dark Blue", "Carnation Pink") as $value) {
    if (strpos($value, $search_for) !== false) {
        echo "Found $value<br/>";
    }
}

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.