Jump to content

[SOLVED] Help detecting a word in an array


limitphp

Recommended Posts

I have a variable $genres

$genres can equal anything from one to many genres.  They are seperated by commas and they have single quotes around all of them.

example values of $genres:

$genres = 'Jazz'

 

or

$genres = 'Jazz,'Blues','Rock','Folk','Indie'

 

is there a way to detect if a word is in genre like Jazz?

 

I'm going to need to check for all genres individually to see if they are in the array.

The reason is because if they already selected it, I want the checkbox to keep it checked

 

example:

if($genres=='Jazz'){		
  echo "<input type='checkbox' name='genre' value='Jazz' CHECKED />";}
else{
  echo "<input type='checkbox' name='genre' value='Jazz' />";}

 

Thanks

 

$lookingFor = "Jazz";
if(strstr($genres, $lookingFor)) {
echo "Found: ".$lookingFor;
}

 

I would prefer to explode each item into an array as such (get rid of the quotes an leave the commas):

 

$items = explode(",",$genres);
$lookingFor = "Jazz";
if(in_array($lookingFor, $items)) {
echo "Found: ".$lookingFor;
}

$lookingFor = "Jazz";
if(strstr($genres, $lookingFor)) {
echo "Found: ".$lookingFor;
}

 

I would prefer to explode each item into an array as such (get rid of the quotes an leave the commas):

 

$items = explode(",",$genres);
$lookingFor = "Jazz";
if(in_array($lookingFor, $items)) {
echo "Found: ".$lookingFor;
}

 

This is going to be on the index page and will be hit quite often.  Do you know which one will be less taxing to the server?

in_array or strstr?

You want to use in_array() really and split your items into array elements.

The strstr() function will also find substrings so it would find Jazz in both 'Jazz' & 'Jazzy' that may cause a problem.

 

Neither of these will tax a server, you are talking microseconds!

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.