php if echo something else echo else for html - php

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.

Related

PHP if/else without echo

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.

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.

How to echo inside html tags

Embedding php inside html </p>
<?php
$text ='Click here';
$link = 'http://www.google.com';
?>
<php? echo $text; ?>
Why is this not printing out link and text assigned in the php code inside the html tags?
If you'll always be running your code in PHP 5.4+, you could use short echo tags;
<?php
$text ='Click here';
$link = 'http://www.google.com';
?>
<?= $text ?>
Looks a little neater in my opinion, but it's a matter of preference, and short echo tags aren't on by default in earlier versions of PHP, so I wouldn't recommend it if your code is ever going to run on server with PHP versions below 5.4
Another way
Embedding php inside html </p>
<?php
$text ='Click here';
$link = 'http://www.google.com';
echo ''.$text.'';
?>
Use sprint
<?php
$text ='Click here';
$link = 'http://www.google.com';
echo sprintf(" %s", $link, $text);
?>
Use this
Embedding php inside html </p>
<?php
$text ='Click here';
$link = 'http://www.google.com';
?>
<?php echo $text; ?>
It is <?php not <php?
use the below code
<?php echo $text; ?>
For the server to interpret your php you need to close all your php code inside the <?php ?> tags and then echo that variable
Open PHP tags properly
You can embedd PHP inside tag as like :
<?php echo $text;?>

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 $_server name and uri

Hi I'm trying to get a piece of html to only show on the main page which is http://www.domain.com/ ... I wrote the code below but it doesn't work the HTML is showing regardless of the page, am I missing something
<?php
$hweb .= 'http://' .$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
if ($hweb == 'http://www.domain.com/'):
?>
<div style="margin:0 auto;">
<div style="float:left">
<?php endif; ?>
First of all - please change
$hweb .= 'http://' .$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
into
$hweb = 'http://' .$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
$hweb may be initialized somewhere before.
Second:
As long as you request 'http://www.domain.com/somename.php' your if condition will never get executed. REQUEST_URI will always hold '/somename.php' except you use some url rewriting.
Third:
Make sure all calls go to 'http://www.domain.com' and not to 'http://domain.com'. Subdomain configurtaions sometimes are very complicated.
At the risk of getting it wrong again..
Why not initialize a variable in the main file before including the header
<?php
$mainfile = true;
?>
then in the header
<?php
if ($mainfile===true)
....
This way the main file can be called anything and be placed anywhere.
Solution 1:
If the above code is written inside 'http://www.domain.com/index.php' file then it may work fine.
Solution 2:
else make sure that $hewb is set with null value earlier b4 this code so that ".=" would not add extra value b4 'http...'.
Now
$hweb = '';
echo $hweb .= 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
That is because the the HTML is inline in the php file but outside of the PHP tags. You can simply echo the HTML inside the if.
if ($hweb == 'http://www.domain.com/')
{
echo '<div style="margin:0 auto;">';
echo '<div style="float:left">';
}
or if you have lots of HTML you could do it like this
<?php
ob_start();
?>
<html>
<body>
<p>This HTML only be echoed </p>
</body>
</html>
<?php
$hweb .= 'http://' .$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
if ($hweb == 'http://www.domain.com/'):
{
ob_end_flush();
}
else
{
ob_end_clean(); // Probably not needed
}
?>

Categories