Link to home
Start Free TrialLog in
Avatar of LB1234
LB1234

asked on

Why did I first need to declare this variable in PHP?

Please see the following code:  the commented line below marks the variable PHP demanded I declare, but I use variables all the time without declaring them first.  Why did PHP throw an error?  I knew the remedy but wanted to expand my understanding. Thanks.

<?php

$selected_car = "chevy";

$car_choices = array ("ford", "chevy", "dodge");

//without declaring this variable I get an error?
$options = "";


foreach ($car_choices as $car_choice) {
	
	$selected = ($selected_car == $car_choice) ? "selected"	: "";
	$options .= "<option $selected % {$car_choice}>{$car_choice}</option>";
	
}


?>

<select>

<?php echo $options ?>

</select>

Open in new window

SOLUTION
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Avatar of Radek Baranowski
Radek Baranowski
Flag of Poland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of LB1234
LB1234

ASKER

This may sound really dumb, but aren't I defining it at line 14?   How is what I'm doing on line 14 any different than what I did with $selected on line 13?
Avatar of LB1234

ASKER

Thanks Gents!
here you are making actual initialization by assignment:
$selected = ($selected_car == $car_choice) ? "selected"      : "";

and here, you try to assign (initialize) $options value of uninitialized variable $options:
$options .= "<option $selected % {$car_choice}>{$car_choice}</option>";

is it clear enough ?