Wordpress Themes - Wordpress Themes - Internet Advertising - Submit articles - WoW Gold

PDA

View Full Version : More flexibility in searching an array


jayg5000
Feb 29th 2008, 1:51 pm
I am trying to search an array to see if it contains a certain word but the in_array(); function (form what I can see) needs to be the exact value of the array values. Here is an example:

$fruit = array('Green Apple', 'Yellow Banana', 'Red Cherry');

How would I search $fruit to see if it contains the word "Green" or "Cherry?" Maybe I'm thinking so hard I can't see the simple solution. Thanks for any help.

RoscoeT
Feb 29th 2008, 6:26 pm
You could use foreach and loop through the array preforming a strpos on each element.

Try something like this untested copied and pasted junk...


$fruit = array('Green Apple', 'Yellow Banana', 'Red Cherry');

foreach ($fruit as $mystring){
$findme = 'Green';
$pos = strpos($mystring, $findme);

// Note our use of ===. Simply == would not work as expected
// because the position of 'a' was the 0th (first) character.
if ($pos === false) {
echo "The string '$findme' was not found in the string '$mystring'";
} else {
echo "The string '$findme' was found in the string '$mystring'";
echo " and exists at position $pos";
}
}