Page 1 of 1

IF statement inside echo

Posted: Mon Oct 12, 2009 3:36 pm
by phpnoobyyy
Hi guys

As my name suggests, i'm new to php so please go easy on me.

I'm trying to output (unsuccessfully thus far) the following inside an echo:

Code: Select all

 
echo '
<li><a href="prices.php" class="topnav1">Prices</a></li>
<li><a href="order.php" class="prinav">Place an order</a></li>
<li class="linav"><?php if ( (isset($_SESSION[\'user_id\'])) && (!strpos($_SERVER[\'PHP_SELF\'], \'sign_out.php\')) ) {
echo \'<a href="sign_out.php">Sign out</a>\';}
else {
echo \'<a href="sign_in.php">Sign in</a>\';
}       
?></li>';
 
Here's the same php code outside the

Code: Select all

bubble:
 
echo '
<li><a href="prices.php" class="topnav1">Prices</a></li>
<li><a href="order.php" class="prinav">Place an order</a></li>
<li class="linav"><?php if ( (isset($_SESSION[\'user_id\'])) && (!strpos($_SERVER[\'PHP_SELF\'], \'sign_out.php\')) ) {
echo \'<a href="sign_out.php">Sign out</a>\';}
else {
echo \'<a href="sign_in.php">Sign in</a>\';
}       
?></li>';
 
I've googled for solutions but nothing seems to work. Help greatly appreciated....thanks
 
PHPnoobyyy

Re: IF statement inside echo

Posted: Mon Oct 12, 2009 4:02 pm
by superdezign
An echo statement must be in <?php ?> tags. You can't have <?php ?> tags inside of <?php ?> tags.

Code: Select all

echo '<li><a href="prices.php" class="topnav1">Prices</a></li>'
   . '<li><a href="order.php" class="prinav">Place an order</a></li>'
   . '<li class="linav">';
 
if ( (isset($_SESSION['user_id'])) && (!strpos($_SERVER['PHP_SELF'], 'sign_out.php')) ) {
    echo '<a href="sign_out.php">Sign out</a>';
} else {
    echo '<a href="sign_in.php">Sign in</a>';
}
 
echo '</li>';

Re: IF statement inside echo

Posted: Mon Oct 12, 2009 4:02 pm
by John Cartwright
You cannot embed php inside a string, you will either need to break out of php or build the string sequentially.

Code: Select all

$output = '
   <li><a href="prices.php" class="topnav1">Prices</a></li>
   <li><a href="order.php" class="prinav">Place an order</a></li>
   <li class="linav">
';
 
if ( (isset($_SESSION['user_id'])) && (!strpos($_SERVER['PHP_SELF'], 'sign_out.php')) ) {
   $output .= '<a href="sign_out.php">Sign out</a>';}
else {
   $output .= '<a href="sign_in.php">Sign in</a>';
}      
$output .= '</li>';
 
echo $output;

Re: IF statement inside echo

Posted: Mon Oct 12, 2009 4:17 pm
by phpnoobyyy
That's great, it works.

Thanks a lot, really appreciated.