Log in

View Full Version : echo inside an echo?



crobinson42
05-19-2010, 10:35 PM
i have a drop down box, which i would like to have the already stored variable selected when the drop down list is produced. here's my example:


<select name="location1"><option selected="selected" value="0">
<?php

require_once('../connectvars.php');

$query = "SELECT * FROM location ORDER BY name ASC";
$result = mysqli_query($dbc, $query);
while($row = mysqli_fetch_array($result)){
$id = $row['id'];
$name = $row['name'];
$address_city = $row['address_city'];
$address_state = $row['address_state'];

$a = if($location1 == '$id'){ echo 'selected="selected"';}

echo '<option value="'.$id.'" '.$a.'> '.$name.', '.$address_city.' '.$address_state.'</option>';
}
?></select>


As you can see, i am trying to create the matching id's and have that option selected..but it doesn't work

Parse error: syntax error, unexpected T_IF

crobinson42
05-20-2010, 01:05 AM
Well Cory, the answer to your question is:

you cannot set a variable as an if() statement.

And to accomplish your task, use this code:


if($location1 == $id) { echo '<option selected="selected" value="'.$id.'" > '.$name.', '.$address_city.' '.$address_state.'</option>'; }
else{
echo '<option value="'.$id.'" > '.$name.', '.$address_city.' '.$address_state.'</option>';}
}

crobinson42
05-20-2010, 01:05 AM
WoW! Thanks Cory for helping me with my Question!! Your awesome!!

crobinson42
05-20-2010, 01:15 AM
now that's a classic example of doing the work yourself to find the answer! BUT, sometimes a little user input helps..

djr33
05-20-2010, 02:25 AM
I *believe* that if you surround anything with () or {} -- it may depend on the context which to use -- that you can get it to actually store that value, but that's only theoretical-- the value of an if is true or false, nothing more.


There is a short way to do this (and I think that's what you were looking for). Check this out:
$a = ($x==1)?1:0;

That can be read as "$a equals: if $x is 1 then 1, else 0"

It's the same as:
if ($x==1) { $a=1; }
else { $a=0; }

For short statements like that, it can be useful:
(condition)?[if true]:[else];

(And it gives this value, you can echo the whole thing or set a variable to it, etc.)


Also, in your initial code, you wouldn't want this:
$a = echo '1';

You just use:
$a = 1;.


Looks like you figured it out, though.

crobinson42
05-20-2010, 02:32 AM
Thanks Dan,

I like your version of the code better:

$a = ($x==1)?1:0;


a lot shorter and kind of fancy!