Forum Moderators: coopster
first I had this
$category.="<option value=\"$row[category_id]\">$row[category_name]</option>";
then I tried:
$category_id=$row['category_id'];
$category_name=$row['category_name'];
$category.="<option value=$category_id>$category_name</option>";
both work but throw an error.
Using the usual var=""; kills the error but kills the row value as well, so it's not an option
[pre]
$category;
while($row = ....) {
$category.="<option value=\"{$row['category_id']}\">{$row['category_name']}</option>";
....
}
[/pre]
$category = '';
Sorry, you actually have to initialize it to something. Thought you didn't but you do
Technically, you are not required to do so, but it will throw a NOTICE error if you don't. There is a note on the PHP variables [php.net] manual page ...
E_NOTICE level error is issued in case of working with uninitialized variables, however not in the case of appending elements to the uninitialized array.
... and a bunch of examples listing "what-ifs" when you don't initialize a variable first. Best practice is to always initialize it, and to initialize it to the type that you intend for usage, be that a string, array, boolean, etc.
I believe the part of initializing that is "unsaid" here is the expression. You need to assign an expression to a variable (or reference) otherwise you are going to get the NOTICE errors.
The braces are the secondary part, henry0. Your issue was the uninitialized variable. More on the braces part here ...
You have all kinds of options when it comes to using array indexes in strings, but the easiest, cleanest way to do it is to use the braces as demonstrated, IMHO. For clarification though, you actually don't have to break out of a string expression when using associative indexes within the string expression. You leave the quotation marks off though because constants are not looked for within strings:
$arr = array('fruit' => 'apple', 'veggie' => 'carrot');
print "Hello $arr[fruit]"; // Hello apple (no errors)