Re: foreach

From: Date: Tue, 16 Oct 2012 23:25:08 +0000
Subject: Re: foreach
References: 1 2 3  Groups: php.general 
Request: Send a blank email to php-general+get-319495@lists.php.net to get a copy of this message
On 10/15/12 9:05 PM, David McGlone wrote:
On Monday, October 15, 2012 08:21:23 PM you wrote:
Bastien Koert On 2012-10-15, at 8:16 PM, David McGlone <david@dmcentral.net> wrote:
I've been sitting here playing around with foreach() and I'm wondering why I am getting these results. here's what I've been fooling around with. the code has no perticular meaning, but I noticed if the script fails, I get the sentence "Too expensive I'm going home LOL" 6 times because there are 6 words in the sentence. I also have a database that looks like this:
product_id        product        price
1                Milk        2.59
2                bread        1.05
And when $row is equal to 0 the output I get is 1 1 Milk Milk 2.59 2.59 Which is printed to the screen according to how many rows are in the db I belive. So my question is why this behavior? I was expecting something like a while loop.
Dave, Foreach is an iterator over an array. Your $row is a pointer to a db result set. If you were to pass the $row result set to the foreach as an array, you'd get what you think you should Www.php.net/foreach
Thanks Bastien. Heres what I started with: $result = mysql_query("SELECT * FROM items"); $row = mysql_fetch_array($result); foreach($row as $rows){ $row = 0; if($row == 0){ echo $rows; } else{ echo "Too expensive I'm going home LOL"; } } Here's what I ended up with after you gave me the advise: $result = mysql_query("SELECT * FROM items"); $rows = array(); while($row = mysql_fetch_array($result))
    $rows[] = $row;
foreach($rows as $row){ $product = $row['product']; $price = $row['price'];
     echo "$product ";
     echo "$price ";
     $justright = 0;
     $toohigh = 5; //I was going to use this to check if the price was too high
just so I could use an elseif in the exercise, but I realized that it would only work if the if() evaluated to false, which would be impossible. Ahhh pizz on it, it was fun anyway! :-)
     if($justright <= $price){
      echo "Not bad. I'll buy it.<br />";
       } else
      echo "Too expensive I'm going home LOL ";
}
For the love of god, please stop using ext/mysql (aka the mysql_* functions). It's insecure and slow and lacks features. Instead, use PDO, and bind your parameters. As a nice bonus, the result from a PDO-based query is not a raw resource but an iteratable object, which means you can foreach() it. http://php.net/manual/en/book.pdo.php $conn = new PDO(...); $result = $conn->query("SELECT * FROM items"); foreach ($result as $record) { // Do something with each record here. } --Larry Garfield

« previous php.general (#319495) next »