Author Topic: [SOLVED] Help detecting a word in an array  (Read 196 times)

0 Members and 1 Guest are viewing this topic.

Offline limitphpTopic starter

  • Devotee
  • Posts: 688
    • View Profile
[SOLVED] Help detecting a word in an array
« on: November 19, 2008, 12:45:00 PM »
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:
Code: [Select]
if($genres=='Jazz'){
  echo "<input type='checkbox' name='genre' value='Jazz' CHECKED />";}
else{
  echo "<input type='checkbox' name='genre' value='Jazz' />";}

Thanks

Offline neil.johnson

  • Guru
  • Fanatic
  • *
  • Posts: 3,411
  • Gender: Male
    • View Profile
Re: Help detecting a word in an array
« Reply #1 on: November 19, 2008, 12:50:13 PM »
Code: [Select]
$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):

Code: [Select]
$items = explode(",",$genres);
$lookingFor = "Jazz";
if(in_array($lookingFor, $items)) {
 echo "Found: ".$lookingFor;
}
« Last Edit: November 19, 2008, 12:51:30 PM by neil.johnson »
Quote
To start, press any key. Where's the 'Any' key?

Offline limitphpTopic starter

  • Devotee
  • Posts: 688
    • View Profile
Re: Help detecting a word in an array
« Reply #2 on: November 19, 2008, 12:57:05 PM »
Code: [Select]
$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):

Code: [Select]
$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?

Offline neil.johnson

  • Guru
  • Fanatic
  • *
  • Posts: 3,411
  • Gender: Male
    • View Profile
Re: Help detecting a word in an array
« Reply #3 on: November 19, 2008, 01:00:50 PM »
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!
Quote
To start, press any key. Where's the 'Any' key?

Offline limitphpTopic starter

  • Devotee
  • Posts: 688
    • View Profile
Re: Help detecting a word in an array
« Reply #4 on: November 19, 2008, 01:45:44 PM »
Thanks!