Foreach Question

I’m just learning to work with arrays, and someone introduced me to the foreach function on another thread. My experiments are kind of working, but something isn’t clicking. I’ve looked at the PHP Manual at http://php.net/manual/en/control-structures.foreach.php but I don’t really get it.

From the beginning, I have a database table (gz_life) that lists the names of thousands of animal species. A second table (gz_ghosts) lists animals that are somehow different from the others, including species that are extinct. The field TaxonG lists animal names and matches the URL’s of some pages. For example, the mastodon page at MySite/Life/Mammutidae matches the TaxonG value “Mammutidae.”

The field Wild_Card groups pages according to what makes them unique - e.g. Extinct (recently), Ice Age (extinct over 10,000 years ago), etc.

So here’s my query:


<?php
$result = mysql_query('select count(*) from gz_ghosts');
if (($result) && (mysql_result ($result , 0) > 0)) {
} else {
die('Invalid query: ' . mysql_error());
}
{

$Children = mysql_query ("SELECT N, TaxonG, Wild_Card
 FROM gz_ghosts
WHERE Wild_Card = 'Ice_Age'");
}

// Note that I'm selecting only rows that represent Ice Age creatures in the above query.

while ($row = mysql_fetch_array($Children, MYSQL_ASSOC))
{
$TaxonG = $row['TaxonG'];
$Wild_Card = $row['Wild_Card'];

// Next, I put the names of all the animals that lived during the Ice Age in an array named $Icy...
$Icy = array($TaxonG);
?>

Now I’m trying to figure out how to manipulate the data in that array. For example, suppose I want to display something only on pages representing extinct animals, like these…

MySite/Life/Mammoth
MySite/Life/Sabertooth_Cat

I do NOT want to display it on pages representing living animals…

MySite/Life/Moose

Assuming I’ve correctly captured the values “Mammoth” and “Sabertooth_Cat” in my array, how can I do that?

I discovered the in_array function, which kind of helps, but I can only use it in very limited ways. I tried a basic foreach function someone gave me:


foreach ($Icy as $k => $v) {
  if ($v == "Mammutidae") {
    echo "Mammoth";
  } // Or any other control structure.
}

If I replace $v with $MyURL, then it will work on the page with that specific URL…


foreach ($Icy as $k => $v) {
  if ($MyURL == "Mammutidae") {
    echo "Mammoth";
  } // Or any other control structure.
}

But I’d like to replace “Mammutidae” with a value representing EVERYTHING in the array, so it will work with Mammutidae or with Mastodon, Sabertooth-Cat, etc.

Here’s one of my experiments with the in_array function:


if (in_array($TaxonG, $Icy)) {
    echo "Hello World";
}

However, it displays values for EVERY row representing the Ice Age…

If I replace $TaxonG with $MyURL, then it displays nothing, because I don’t know how to associate the page’s URL with the contents of the array.

I’ve also tried experiments like this:


switch($MyURL)
{
 // case array($Icy):
 case (in_array($TaxonG, $Icy)):
 echo 'Whatever';
 break;
 default:
 echo 'DEFAULT';
 break;
}
}

Anyway, can someone tell me how to manipulate the array $Icy so I can associate it with URL’s matching its contents? Also, is there a way to display all the values in that array, so I can verify that it’s working the way I want it to?

Thanks.

P.S. I should mention that I’ve tried my experiments both inside and outside the while loop.

Lets have a look.
Simple things first:

Also, is there a way to display all the values in that array, so I can verify that it’s working the way I want it to?

print_r($myarray) OR var_dump($myarray) will dump you the entire array.

As for associating an url with $icy…
You are pulling animal names(your TaxonG field) into the array $icy. i assume that is the only thing in it.

$Icy = array
(
  0 => 'Mammutidae'
);

We could make a multidimensional array. like this:

$Icy = array
(
  0 => array
         (
          taxon => mammutidae
          url => mysite/life/mammutidae
         )
  1 => array //next taxon and its url
)

We can work with the above array, check urls or taxons with a control structure.
Does it sound like this might help, or am i off the mark?

Thanks for the tips. Give me a few minutes to play with your code and see if I can figure it out. (Actually, it will probably take me half an hour; I’m pretty slow at figuring these things out. ;))

On second thought, that was fast. The two scripts you gave me for displaying the contents of an array work great.

I don’t understand exactly how the other code works, but I made a few minor changes to adapt it to my code…


$Icy = array
(
  0 => array
         (
          $TaxonG => Mammutidae
          $MyUrl => Mammutidae
         )
  1 => array //next taxon and its url
)

I am getting error messages - syntax error, unexpected T_VARIABLE, expecting ‘)’; I’m probably just missing a colon or semicolon somewhere or need to replace some of the parentheses with brackets maybe?

But, yes, your code looks interesting. Thanks again.

I didnt actually try running the array… this code should work:

<?php
$Icy = array (
	      0 => array (
			  'TaxonG' => 'Mammutidae',
			  'MyUrl' => 'Mammutidae'
			  ),
	      1 => array() //next taxon and its url
	      );
?>

Another thing, mysql_* functions are quite old and unsecure by default. You should look into mysqli or [URL=“http://php.net/manual/en/book.pdo.php”]PDO.

Secondly, if you are going to make an array like the above, and fill it in in a loop, we could do it like this:

$Icy = array();
$i = 0;
while ($row = mysql_fetch_array($Children, MYSQL_ASSOC))
{
  $Icy[$i]['taxon'] = $row['TaxonG'];
  $Icy[$i]['MyUrl'] = $TheUrl; // You need to get the URL or generate it...
  $i++;
}

Try dumping the above array, should show you a thing or two.

Also, just tinkering around, you should learn the ins and outs of arrays and handling them in a few days.


<?php
$result = mysql_query('select count(*) from gz_ghosts');
if (($result) && (mysql_result ($result , 0) > 0)) {
} else {
die('Invalid query: ' . mysql_error());
}

I don’t see the use of this piece of your code. What do you do with that count in the rest of your script?


// Next, I put the names of all the animals that lived during the Ice Age in an array named $Icy...
$Icy = array($TaxonG);
?>

This does not put all animal names in an array. It creates a new array with only one element (the animal retrieved at that moment) each time.
To get an array with all names, change it in


// Next, I put the names of all the animals that lived during the Ice Age in an array named $Icy...
$Icy[] = $TaxonG;
?>

Then loop through the array you created, using the $v (value) directly, instead of comparing it with fixed values in a switch, array or if-else structure. You want to use all names you found in the database, and you want to do the same thing with all of those names, so you can do this:


foreach ($Icy as $k => $v) {
  echo "Mysite/Life/$v";
  } 
}

Complete code:


$Children = mysql_query ("
  SELECT N, TaxonG, Wild_Card
  FROM gz_ghosts
  WHERE Wild_Card = 'Ice_Age'
");

$Icy = array ()   // initialize the empty array
while ($row = mysql_fetch_array($Children, MYSQL_ASSOC)) {
  // add each name to the array
  $Icy[] = $row['TaxonG'];
}

foreach ($Icy as $k => $v) {
  // display each name in the array
  echo "Mysite/Life/$v";
}

I second this.

Wow, thanks for all the tips. I have a working script now, though I still have to work out a few kinks.

I knew MySQL has been around for a while, but I didn’t realize it was insecure. The folks in charge must not be doing a good job of upgrading it, huh? I’ll have to check out mysqli and PDO.

PDO and MYSQLI both still connect to mysql. It’s not mysql that’s insecure, but the actual mysql_ functions within php. I would recommend learning PDO and prepared statements. It will save you a lot pain regarding future security, so it’s well worth the effort to learn.