Page 1 of 1

Undefined variable error with Array

Posted: Wed Aug 14, 2013 3:34 pm
by Jano12
This are the errors I get : Notice: Undefined variable: furn_categories in C:\xampp\htdocs\shopcart\Ch04\page_furniture_index.inc on line 31

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\shopcart\Ch04\page_furniture_index.inc on line 31

Here's a code snippet from the first file Catalog.php:

***** PLEASE USE PHP CODE TAGS AROUND YOUR CODE *****

Code: Select all

while($row = mysqli_fetch_array($result))              	#64

	{

		$furn_categories[$row['category']][]=$row['type'];

	}

	include("page_furniture_index.inc");                   	#68

}

?>
Code snippet from the INC file, where the error is, which is included in the Catalog.php file above :

Code: Select all

foreach($furn_categories  as $key => $subarray)	#31

{

	echo "<li>$key</li>\n";	#33

	echo "<ul>\n";	#34

	foreach($subarray as $type)	#35

	{

		echo "<li class='level2'>

		<input type='radio' name='interest'

		id='$type' value='$type' /> 

		<label for='$type'>$type</label></li>\n";

	} // end foreach type	#41
Please help me solve that misunderstanding unidentified var when the var was declared in the Catalog.php as $furn_categories[$row['category']][]=$row['type']; in the Catalog.php isn't it enough ?

Re: Undefined variable error with Array

Posted: Wed Aug 14, 2013 4:51 pm
by requinix
Jano12 wrote:Please help me solve that misunderstanding unidentified var when the var was declared in the Catalog.php as $furn_categories[$row['category']][]=$row['type']; in the Catalog.php isn't it enough ?
That's not declaring it. That's adding a value to an array. If that array doesn't exist yet then PHP will very nicely create it for you without raising any sorts of warnings.

Consider this: what will happen if your SQL query doesn't find any rows? What will be the value of $furn_categories? Now that you understand that, initialize the variable (with an empty array) before your while loop - that way it exists, and is an array, regardless of whether there were rows or not.

Re: Undefined variable error with Array

Posted: Fri Aug 16, 2013 2:03 pm
by Jano12
I've initialized it with

Code: Select all

$furn_categories[][]= 1;
it worked although I have some other errors which I have to resolve and it shows me 1 at the php Catalogt.php, but how else I can initialize it?

Re: Undefined variable error with Array

Posted: Fri Aug 16, 2013 2:48 pm
by Christopher
Jano12 wrote:, but how else I can initialize it?
Since you are going to load it with data from the database, you should initialize it like:

Code: Select all

$furn_categories = array();
Then if nothing is loaded, following foreach() loops won't error.