PHP if/else without echo - php

How do I replace echo with proper html codes? Since there will be hundreds of html codes, using echo doesn't make sense.
<?php
if ($this->item->catid == 9) {
echo "yes, it exists";
}
else {
echo "no, it don't exist";
}
?>
I'm new to PHP.

Do you mean, how can one cleanly output many lines of HTML conditionally without having to echo each individual line?
If that's the case, something like this would do the trick:
<?php
if ($this->item->catid == 9) {
?>
<!--- put all the raw output you like here --->
<?php
} else {
?>
<!--- put all the raw output you like here --->
<?php
}
?>
The "raw output" would be anything sent to the browser. HTML, JavaScript, etc. Even though it's outside of the server-side PHP tags, as far as the PHP processor is concerned it's still between the { ... } brackets. So it's only output as part of that conditional block.

There is two way to do it :
1) As suggested by David, by closing your php tags to write raw HTML.
<?php
if ($this->item->catid == 9) {
?>
// HTML goes here
<?php
}else{
?>
// HTML goes here
<?php
}
?>
But if you're planning to write a lot of text it might be a be hard to read your code in the end so you can use the following.
<?php
$htmlOutput = '';
if ($this->item->catid == 9) {
$htmlOutput .= "yes, it exists";
} else {
$htmlOutput .= "no, it doesn't exist";
}
?>
You create a variable that will contain all your HTML by appending a part of it everytime you need to so in the end you'll only need to print a single variable.

Related

having php indent properly on echo?

I recently created a new login-register system for myself but i'm having issues with htmls indenting when echoed from php, Now that i've really looked at it, i realized that echoing a entire page isnt the smartest idea, unless it is?
<?php
if (isset($_SESSION['sessionId'])) {
echo('This is the new content after login.');
} else{
echo 'This is the login page';
}
?>
above is my index.php the first echo would echo the entire page of content the user would see after they logged in.
Second is the login form.
what would be the easiest way to go about this?
You can do something like this
<?php
if (isset($_SESSION['sessionId'])) {
readfile("/path/to/html/file/new_content.html");
} else{
readfile("/path/to/html/file/login.html");
}
?>
You can try echoing your HTML output like so
&lt?php
if (isset($_SESSION['sessionId'])) {
echo '&ltbr&gt&ltp&gt';
echo'This is the new content after login.';
echo '&lt/p&gt';
} else{
echo '&ltbr&gt&ltp&gt';
echo '&nbsp&nbspThis is the login page';
echo '&lt/p&gt';
}
?&gt
You'll see the above code in view source if you use it
Output:
<br>
<p>
&nbsp&nbspThis is the content after login
</p>
second output
<br>
<p>
&nbsp&nbspThis is the login page
</p>
P.S. BTW why are you using brackets for one echo and none for the other
???

if Else php need explanation

i write a code in php and i found that there is a problem in a code like this :
<?php if(isset($_GET['f'])) { ?>
<?php if($_GET['f']=="message_reçus") { ?>
-- another code here --
<?php } ?>
<?php } ?>
<?php else { ?>
But when i just write it this way :
<?php if(isset($_GET['f'])) { ?>
<?php if($_GET['f']=="message_reçus") { ?>
-- another code here --
<?php } ?>
<?php } else { ?>
It works.
I need a clear explanation about what caused the problem in the first version because i still convinced that both version are syntactically right!
PHP Parser shows me : Parse error: syntax error, unexpected 'else' (T_ELSE)
I don't need any alternative solution i just wonder to know why there is a problem in the first version and what's wrong with it!
One way to think about it is to replace ?> ... <?php with echo "...";
So your code becomes:
<?php
if(isset($_GET['f'])) {
echo "\n\t";
if($_GET['f'] == "message_reçus") {
echo "\n\t\t";
// more code here
echo "\n\t";
}
}
echo "\n"; // problem!
else {
// ...
}
Whereas if you just have } else { you don't have that extra echo "\n"; in the way.
The description to the problem was detailed in a different answer by #NietTheDarkAbsol. I'm adding this answer to add an alternative solution to the problem by removing it.
The problem exlained (#NietTheDarkAbsol answer describes this)
By separating out the lines you add in a \n or new line whereas else MUST always come after the closing brace of the opening if.
<?php if ($a === $b) { ?>
<?php } ?>
<?php else { ?>
This is interpreted as if ($a === $b) { \n } \n else {
The \n or new line after the ifs closing bracket removes any ability for the parser to understand that the else is associated with the if and throws the error.
An alternative approach to remove a requirement for curly braces.
An approach that is particularly useful when interpolating HTML files with PHP is to use an alternative control structure that removes the need for braces. This will also help you in your current predicament as well as making your code look a little cleaner.
<?php if(isset($_GET['f'])) : // Colon instead of an '{' ?>
<?php if($_GET['f']=="message_reçus") : ?>
<!-- HTML here -->
<?php else : ?>
<!-- alternative HTML here -->
<?php endif; // endif; instead of an '}' ?>
<?php endif; ?>
As your code is now non reliant on curly braces your problem vanishes as it is waiting for either an endif;, else : or elseif (...) : block.

PHP script tags

Why does this if statement have each of its conditionals wrapped in PHP tags?
<?php if(!is_null($sel_subject)) { //subject selected? ?>
<h2><?php echo $sel_subject["menu_name"]; ?></h2>
<?php } elseif (!is_null($sel_page)) { //page selected? ?>
<h2><?php echo $sel_page["menu_name"]; ?></h2>
<?php } else { // nothing selected ?>
<h2>Select a subject or a page to edit</h2>
<?php } ?>
Because there is html used. Jumping between PHP and HTML is called escaping.
But I recommend you not to use PHP and HTML like this. May have a look to some template-systems e.g. Smarty or Frameworks with build-in template-systems like e.g. Symfony using twig.
Sometimes its ok if you have a file with much HTML and need to pass a PHP variable.
Sample
<?php $title="sample"; ?>
<html>
<title><?php echo $title; ?></title>
<body>
</body>
</html>
This is not much html but a sample how it could look like.
That sample you provided us should more look like....
<?php
if(!is_null($sel_subject))
{ //subject selected?
$content = $sel_subject["menu_name"];
}
else if (!is_null($sel_page))
{ //page selected?
$content = $sel_page["menu_name"];
}
else
{ // nothing selected
$content = "Select a subject or a page to edit";
}
echo "<h2>{$content}</h2>";
?>
You could echo each line of course. I prefer to store this in a variable so I can easy prevent the output by editing one line in the end and not each line where I have added a echo.
According to some comments i did a approvement to the source :)
Because the <h2> tags are not PHP and will display an error if the PHP Tags are removed.
This code will display one line of text wrapped in <h2> tags.
This is called escaping.
Because you cannot just type html between your php tags.
However, I would rather use the following syntax because it is easier to read. But that depends on the programmers opinion.
<?php
if(!is_null($sel_subject))
{ //subject selected?
echo "<h2>" . $sel_subject["menu_name"] . "</h2>";
}
elseif (!is_null($sel_page))
{ //page selected?
ehco "<h2>" . $sel_page["menu_name"] . "</h2>";
}
else
{ // nothing selected
echo "<h2>Select a subject or a page to edit</h2>";
}
Because inside the if-statement there is an HTML code, which you can put it by closing PHP tags and open it again like this:
<?php if(/*condition*/){ ?> <html></html> <?php } ?>
or:
<?php if(/*condition*/){ echo '<html></html>' ; }
That is because in this snippet we see html and php code. The code <?php changes from html-mode to php-mode and the code ?> changes back to html-mode.
There are several possibilites to rewrite this code to make it more readable. I'd suggest the following:
<?php
//subject selected?
if (!is_null($sel_subject)) {
echo "<h2>" . $sel_subject["menu_name"] . "</h2>";
//page selected?
} elseif (!is_null($sel_page)) {
echo "<h2>" . $sel_page["menu_name"] . "</h2>";
// nothing selected
} else {
echo "<h2>Select a subject or a page to edit</h2>";
}
?>
using the echo-command to output html, you don't need to change from php-mode to html-mode and you can reduce the php-tag down to only one.

php if echo something else echo else for html

So here's my code, I try to make for my pagination function to echo something if is on homepage and echo else if is on another page like page=2 or page3 ++
<?php if(empty($_GET) or ($_GET['pg']==1)) { echo ' ?> Html codes content and php <?php '; } else { echo '?> Else html codes content and php <?php '; } ?>
But is not working, i'm sure is from the " ' " or " '' " something i put wrong but where? where or what is the problem
Don't put ?> in the echo statement.
<?php
if(empty($_GET) || $_GET['pg'] ==1) {
echo 'HTML codes content';
} else {
echo 'Else html codes content';
}
?>
You can also do it by closing the PHP and not using echo:
<?php
if (empty($_GET) || $_GET['pg'] ==1) { ?>
HTML codes content
<?php else { ?>
Else html codes content
<?php } ?>
You can use a ternary operator to make it simpler. Also it's better to use isset() because even if $_GET is not empty, that doesn't mean that $_GET['pg'] exists, so it will generate warnings.
Anyway as pointed out above, the problem is that you are using ?> inside the echo statement, which is incorrect.
You can do for example:
<?php if ((isset($_GET['pg'])) && ($_GET['pg']==1)) { ?>Html codes content and php<?php } else { ?>Else html codes content and php<?php } ?>
Using a ternary operator:
<?php echo ((isset($_GET['pg'])) && ($_GET['pg']==1)) ? 'Html codes content and php' : 'Else html codes content and php'; ?>
Using a ternary operator and short tags:
<?=((isset($_GET['pg'])) && ($_GET['pg']==1)) ? 'Html codes content and php' : 'Else html codes content and php'; ?>
You cannot have PHP code in echo, because PHP will interpret your code in a single pass.
Your code should be like this :
<?php
echo (empty($_GET) || ($_GET['pg']==1)) ?
'Html code':
'Another HTML code';
?>
If you need to output some PHP code, there is always a better way to accomplish it, you can include some file that contains the php code you want to add.
You can use this way.
<?php if(empty($_GET) || $_GET['pg'] ==1): ?>
<p>HTML codes content</p>
<?php else: ?>
<p>Else html codes content<p>
<?php endif; ?>
Note that : I used direct html code.

what is wrong with this snippet

<?php } elseif($_SOMETHING == 1 && $_ANOTHER_THING == 2) { ?>
<?php $_NAME = urlencode($_NAME); ?>
<?php $_MGT_NAME = urlencode($_MGT_NAME); ?>
</div>
<?php } ?>
I am getting this error expected ';'
The horror. The horror.
Here's the actual error, in the onclick attribute value:
lpButtonCTTUrl = 'http:...Ad%20Source=somesite.com& ='+escape(document.location); imageUrl=<?php print "http://{$_SERVER['SITENAME']}/images/";?>&referrer
That is, there should be a +' instead of ; after the document.location inclusion, and there should be a closing quote after the imageURL inclusion, and referrer is in the wrong place (it should be just before the document.location inclusion.
It also has problems like the use of escape (never use escape. For URL-encoding you actually want encodeURLComponent); the unescaped ampersands all over the place; and the lack of HTML- and URL-encoding of values output from PHP, potentially causing cross-site scripting risks.
Writing a value inside a URL component inside a URL inside a JavaScript string literal inside an attribute value inside HTML is utter insanity so it's no surprise there are mistakes. Let's try to bring some maintainability to this madness. Break out the JavaScript and URL creation into separate steps where getting the escaping right is possible.
function urlencodearray($a) {
$o= array();
foreach ($a as $k=>$v)
array_push($o, rawurlencode($k).'='.rawurlencode($v));
return implode('&', $o);
}
function h($s) {
echo htmlspecialchars($s);
}
With these utility functions defined, then:
<?php } elseif($_SOMETHING == 1 && $_ANOTHER_THING == 2) { ?>
<?php
$lpbase= 'http://server.iad.liveperson.net/hc/84152841/?';
$linkurl= $lpbase.urlencodearray(array(
'cmd'=>'file',
'file'=>'visitorWantsToChat',
'site'=>'84152841',
'byhref'=>'1',
'skill'=>'somesiteILS',
'SESSIONVAR!skill'=>'somesiteILS',
'SESSIONVAR!Management Company'=>$_MGT_NAME,
'SESSIONVAR!Community'=>$_NAME,
'SESSIONVAR!Ad%20Source'=>'somesite.com',
'imageUrl'=>"http://{$_SERVER['SITENAME']}/images/"
));
$imgurl= $lpbase.urlencodearray(array(
'cmd'=>'repstate',
'site'=>'84152841',
'channel'=>'web',
'ver'=>'1',
'skill'=>'somesiteILS',
'imageUrl'=>"http://{$_SERVER['SITENAME']}/images/"
));
?>
<div id="caller_tag">
<a id="_lpChatBtn" target="chat84152841" href="<?php h($url); ?>">
<img src="<?php h($imgurl); ?>" name="hcIcon" alt="Chat" border="0">
</a>
<script type="text/javascript">
document.getElementById('_lpChatBtn').onclick= function() {
var url= this.href+'&referrer='+encodeURIComponent(location.href);
if ('lpAppendVisitorCookies' in window)
url= lpAppendVisitorCookies(url);
if ('lpMTag' in window && 'addFirstPartyCookies' in lpMTag)
url= lpMTag.addFirstPartyCookies(url)
window.open(url, this.target, 'width=475,height=400,resizable=yes');
return false;
};
</script>
</div>
With an unformatted mess like that it's no wonder you can't find the error.
I tried running it through HTML Tidy but it doesn't like anything between the comments.
mesite.com& ='+escape(document.location); imageUrl=<?php print "ht
I'm not good at reading long lines like that but shouldn't this be
mesite.com& ='+escape(document.location) +'imageUrl=<?php print "ht
First of: why are you opening and closing PHP so many times, you could write it like:
<?php
} elseif($_SOMETHING == 1 && $_ANOTHER_THING == 2) {
$_NAME = urlencode($_NAME);
$_MGT_NAME = urlencode($_MGT_NAME);
?>
<div id="caller_tag">
<!-- BEGIN LivePerson Button Code --><a id="_lpChatBtn" href='http://server.iad.liveperson.net/hc/84152841/?cmd=file&file=visitorWantsToChat&site=84152841&byhref=1&SESSIONVAR!skill=somesiteILS&SESSIONVAR!Management%20Company=<?php print $_MGT_NAME; ?>&SESSIONVAR!Community=<?php print $_NAME; ?>&SESSIONVAR!Ad%20Source=somesite.com&imageUrl=<?php print "http://{$_SERVER['SITENAME']}/images/";?>' target='chat84152841' onClick="lpButtonCTTUrl = 'http://server.iad.liveperson.net/hc/84152841/?cmd=file&file=visitorWantsToChat&site=84152841&SESSIONVAR!skill=somesiteILS&SESSIONVAR!Management%20Company=<?php print $_MGT_NAME; ?>&SESSIONVAR!Community=<?php print $_NAME; ?>&SESSIONVAR!Ad%20Source=somesite.com& ='+escape(document.location); imageUrl=<?php print "http://{$_SERVER['SITENAME']}/images/";?>&referrer lpButtonCTTUrl = (typeof(lpAppendVisitorCookies) != 'undefined' ? lpAppendVisitorCookies(lpButtonCTTUrl) : lpButtonCTTUrl); lpButtonCTTUrl = ((typeof(lpMTag)!='undefined' && typeof(lpMTag.addFirstPartyCookies)!='undefined')?lpMTag.addFirstPartyCookies(lpButtonCTTUrl):lpButtonCTTUrl);window.open(lpButtonCTTUrl,'chat84152841','width=475,height=400,resizable=yes');return false;" ><img src='http://server.iad.liveperson.net/hc/84152841/?cmd=repstate&site=84152841&channel=web&&ver=1&imageUrl=<?php print "http://{$_SERVER['SITENAME']}/images/";?>&skill=somesiteILS' name='hcIcon' alt='Chat Button' border=0></a><!-- END LivePerson Button code -->
</div>
And also: the error must be somewhere else, I can't see a missing ";" in php in the code you pasted, unless the error is in javascript.

Categories