Simple Array Question

I know how to work with simple arrays, like this:


 $That = array('usa', 'mex', 'jpn');
 $This = array('United States', 'Mexico', 'Japan');
 $Text = str_replace($That, $This, $Text);

If you could describe this as a one-on-one script, I’d now like to write a many-on-one script. For example, imagine the following switch:


switch($Taxon)
{
 case 'Canidae':
 $Group = 'Carnivores';
 break;
 case 'Felidae':
 $Group = 'Carnivores';
 break;
 case 'Ursidae':
 $Group = 'Carnivores';
 break;
 default:
 break;
}

Now imagine a similar downstream code that’s in a loop…


switch($Taxon)
{
 case 'Canidae':
 $NewValue = 'Diet';
 break;
 case 'Felidae':
 $NewValue = 'Diet';
 break;
 case 'Ursidae':
 $NewValue = 'Diet';
 break;
 default:
 break;
}

Rather than list all these values (there will hundreds of values) a second time, I’d like to make it simpler, something like this…


switch($Group)
{
 case '$Carnivores':
 $NewValue = 'Diet';
 break;
 default:
 break;
}

But this code doesn’t work. Is there some sort of array I can write that will let me replace an echo value (e.g. $Group) with ANYTHING included in an array? In other words, the switch above would work for any value in my array - Canidae, Felidae or Ursidae.


switch($Taxon)
{
 // $Carnivore = an array that includes the values Canidae, Felidae and Ursidae. Thus, $NewValue will = 'Diet' whether a looped value is Canidae, Felidae or Ursidae.
 case '$Carnivore':
 $NewValue = 'Diet';
 break;
 default:
 break;
}

I hope I explained this right. I was doing this with a database, but that has a few problems of its own, so I want to try it with an array, or whatever works. Thanks.

I thought the in_array function might work, but it doesn’t appear to work in a loop…


$Info = array("Loxodonta", "Canidae", "Felidae");

$Info = array("Loxodonta", "Canidae", "Felidae");
if (in_array("Loxodonta", $Info)) {
    echo "Got Loxodonta";
}
if (in_array("Nachos", $Info)) {
    echo "Got Nachos";
}

This particular page displays three values, including Loxodonta. But the script displays “Loxondonta” three times - once for every row. It might work if I could add some code that says DISPLAY LOXODONTA (or another value in the array) FOR EVERY ROW WHERE $TAXON = ONE OF THOSE VALUES.

foreach ($Info as $k => $v) {
  if ($v == "Loxodonta") {
    echo "got Loxodonta" ;
  } // Or any other control structure.
}

PHP.net on foreach

Should help you work with arrays.

Edit: Corrected missing $

Cool; thanks for the tip! I was up all night playing with arrays. I’ll probably have a few more questions, but I’m getting a handle on them. Wish I had tackled arrays years ago. :wink: