Hello,
I was working on some code, when I ran into this: foreach ($products as $product). One problem, it was not defined. How could this be? Here is the book I got it from: http://english-common.googlecode.com/svn-history/r100/trunk/huyliem/01-Murach.PHP.MySQL/Murach.PHP.and.MySQL.Nov.2010.pdf . It is on 161-163. I don't understand where the $product came from. And one more thing. Doe fetch() turn the mysql variables into arrays? Thanks

Recommended Answers

All 6 Replies

Member Avatar for LastMitch

@vivosmith

I was working on some code, when I ran into this: foreach ($products as $product). One problem, it was not defined. How could this be?

The link you provided didn't work

so for your example: foreach ($products as $product)

You can used this:

<?php
$products = array(1, 2, 3, 4);
foreach ($products as &$product) {
    $product = $product * 2;
}
unset($product); 
?>

If you really want to learn and know how that example works then read this:

http://php.net/manual/en/control-structures.foreach.php

This will give you an idea on how that foreach() function works.

Basically you're saying to loop through the $products array, and for each element in the array, temporarily make it accessible via the $product variable. Do something with this $product variable, and then loop. This way you have access to a single variable name that you can keep reusing for each element in the array. Kinda sorta. I'm bad at explaining.

This file may be included into another script, where the variable has a value.

I figured it out. I believe the foreach statement is creating an array from the previous variable. Am I correcting in saying it goes from variable to array, or is it the opposites?

I see. The catergories variable is a query, and the array variable category stores the results. Thanks

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.