Site prints all PHP instead of using it - php

another problem. I'm making a CMS and I want the login link to disapear when I want to. So I can configure it in my adminCP. When I "flip the switch" my configfunctions.php changes $login to true.
To use it I'm doing:
<?php if($loginenabled = true) { '<li><span class="mmLogin">Login</span></li>' }; ?>
but my site literally prints ALL PHP, also when I do other PHP. So my site looks like:
Home, About us, <?php if($loginenabled = true) { 'login' }; ?>
Does anyone know how to solve it?
Wesley

You can't output HTML code by simply creating a string. To write output, you can use the echo statement:
<?php if ($loginEnabled == true) {
echo '<li><span class="mmLogin">Login</span></li>';
}; ?>
Note the semicolon at the end of the single quotes ('). You can also use PHP's alternate syntax for control structures for cleaner code:
<?php if ($loginEnabled == true): ?>
<li><a href="sample-login.html" class="login">
<span class="mmLogin">Login</span>
</a></li>
<?php endif; ?>
The above will accomplish the same thing. Also note that ($loginEnabled = true) is always true, since = is an assignment operator. To check if $loginEnabled is true, use:
if ($loginEnabled == true)
You can also shorten it to simply:
if ($loginEnabled)
Read more on assignment operators, comparison operators, and the if statement.

Related

Hide html when included inside php if condition

I would like to present some php with the help of html formatting.
My purpose is to print:
Life status: dead (1850 in New-York)
or (if not dead):
Life status: alive
The place and date should only by printed if the condition $life_status is set to "dead".
The following code works for the dead situation but not for the alive one.
<h3>Title</h3>
<ul>
<li>Life status: <?php echo $life_status;?>
<?php if($life_status="dead"):?>
(<?php echo $date_death; ?> in <?php echo $place_death; ?>).
</li>
<?php endif; ?>
</ul>
For the alive sitation, I obtain:
Life status: Alive ( in ).
How can I applied the php condition on "( in)."?
Your operator for checking if $life_status is dead is wrong. It is a single equal and should be double. Code below reflects these changes and implements what #AmericanUmlaut correctly suggested in the comment above to make your html actually valid.
<h3>Title</h3>
<ul>
<li>Life status: <?php echo $life_status;?>
<?php if($life_status == "dead"):?> // This maybe the issue, wrong operator used to evaluate.
(<?php echo $date_death; ?> in <?php echo $place_death; ?>).
<?php endif; ?>
</li>
</ul>
You are using the wrong operator. = is assignment, == tests equality.
<h3>Title</h3>
<ul>
<li>Life status: <?php echo $life_status;?>
<?php if($life_status=="dead"):?> // == here instead of =
(<?php echo $date_death; ?> in <?php echo $place_death; ?>).
<?php endif; ?>
</li>
</ul>
(Note that I also moved the outside of the if block to address the issue I noted in my comment.)
In Php strings are not compared directly and may not give the results which are intended. Therefore, using strcmp(); function will do the work. It returns 0 when 2 strings compared are equal and is a case sensitive function.
In your case:
<h3>Title</h3>
<ul>
<li>
Life status: <?php
echo ( !strcmp($life_status,"dead") ) ? 'Dead ( '.$date_death.' in '.$place_death.' ).' : 'Alive' ;
?>
</li>
</ul>
I have used the Php Ternary operator known as Shorthand if/else.
The ! will reverse the 0 to 1 if its true to show the Dead output and else will show the Alive output.
Php Ternary : http://php.net/manual/en/language.operators.comparison.php
Php strcmp() : http://php.net/manual/en/function.strcmp.php
I hope it helps :)
Regards,
SA

Which is the correct way to write an IF statement of these two? [duplicate]

Are there any differences between...
if ($value) {
}
...and...
if ($value):
endif;
?
They are the same but the second one is great if you have MVC in your code and don't want to have a lot of echos in your code. For example, in my .phtml files (Zend Framework) I will write something like this:
<?php if($this->value): ?>
Hello
<?php elseif($this->asd): ?>
Your name is: <?= $this->name ?>
<?php else: ?>
You don't have a name.
<?php endif; ?>
At our company, the preferred way for handling HTML is:
<? if($condition) { ?>
HTML content here
<? } else { ?>
Other HTML content here
<? } ?>
In the end, it really is a matter of choosing one and sticking with it.
They are indeed both the same, functionally.
But if the endif is getting too far from the correspondent if I think it's much better practice to give a referencing comment to it. Just so you can easily find where it was open. No matter what language it is:
if (my_horn_is_red or her_umbrella_is_yellow)
{
// ...
// let's pretend this is a lot of code in the middle
foreach (day in week) {
sing(a_different_song[day]);
}
// ...
} //if my_horn_is_red
That actually applies to any analogous "closing thing"! ;)
Also, in general, editors deal better with curly brackets, in the sense they can point you to where it was open. But even that doesn't make the descriptive comments any less valid.
Here's where you can find it in the official documentation: PHP: Alternative syntax for control structures
I think that it's particularly clearer when you're using a mix of ifs, fors and foreaches in view scripts:
<?php if ( $this->hasIterable ): ?>
<h2>Iterable</h2>
<ul>
<?php foreach ( $this->iterable as $key => $val ):?>
<?php for ( $i = 0; $i <= $val; $i++ ): ?>
<li><?php echo $key ?></li>
<?php endfor; ?>
<?php endforeach; ?>
</ul>
<?php elseif ( $this->hasScalar ): ?>
<h2>Scalar</h2>
<?php for ( $i = 0; $i <= $this->scalar; $i++ ): ?>
<p>Foo = Bar</p>
<?php endfor; ?>
<?php else: ?>
<h2>Other</h2>
<?php if ( $this->otherVal === true ): ?>
<p>Spam</p>
<?php else: ?>
<p>Eggs</p>
<?php endif; ?>
<?php endif; ?>
as opposed to:
<?php if ( $this->hasIterable ){ ?>
<h2>Iterable</h2>
<ul>
<?php foreach ( $this->iterable as $key => $val ){?>
<?php for ( $i = 0; $i <= $val; $i++ ){ ?>
<li><?php echo $key ?></li>
<?php } ?>
<?php } ?>
</ul>
<?php } elseif ( $this->hasScalar ){ ?>
<h2>Scalar</h2>
<?php for ( $i = 0; $i <= $this->scalar; $i++ ){ ?>
<p>Foo = Bar</p>
<?php } ?>
<?php } else { ?>
<h2>Other</h2>
<?php if ( $this->otherVal === true ){ ?>
<p>Spam</p>
<?php } else { ?>
<p>Eggs</p>
<?php } ?>
<?php } ?>
This is especially useful for long control statements where you might not be able to see the top declaration from the bottom brace.
I think that it really depends on your personal coding style.
If you're used to C++, Javascript, etc., you might feel more comfortable using the {} syntax.
If you're used to Visual Basic, you might want to use the if : endif; syntax.
I'm not sure one can definitively say one is easier to read than the other - it's personal preference. I usually do something like this:
<?php
if ($foo) { ?>
<p>Foo!</p><?php
} else { ?>
<p>Bar!</p><?php
} // if-else ($foo) ?>
Whether that's easier to read than:
<?php
if ($foo): ?>
<p>Foo!</p><?php
else: ?>
<p>Bar!</p><?php
endif; ?>
is a matter of opinion. I can see why some would feel the 2nd way is easier - but only if you haven't been programming in Javascript and C++ all your life. :)
I would use the first option if at all possible, regardless of the new option. The syntax is standard and everyone knows it. It's also backwards compatible.
Both are the same.
But:
If you want to use PHP as your templating language in your view files(the V of MVC) you can use this alternate syntax to distinguish between php code written to implement business-logic (Controller and Model parts of MVC) and gui-logic.
Of course it is not mandatory and you can use what ever syntax you like.
ZF uses that approach.
There is no technical difference between the two syntaxes. The alternative syntax is not new; it was supported at least as far back as PHP 4, and perhaps even earlier.
You might prefer the alternative form because it explicitly states which control structure is ending: endwhile, for example, can only terminate a while block, whereas if you encounter a brace, it could be closing anything.
You might prefer the traditional syntax, though, if you use an editor that has special support for braces in other C-like syntaxes. Vim, for example, supports several keystrokes for navigating to matching braces and to the starts and ends of brace-delimited blocks. The alternative syntax would break that editor feature.
In the end you just don't want to be looking for the following line and then having to guess where it started:
<?php } ?>
Technically and functionally they are the same.
It all depends, personally I prefer the traditional syntax with echos and plenty of indentations, since it's just so much easier to read.
<?php
if($something){
doThis();
}else{
echo '<h1>Title</h1>
<p>This is a paragraph</p>
<p>and another paragraph</p>';
}
?>
I agree alt syntax is cleaner with the different end clauses, but I really have a hard time dealing with them without help from text-editor highlighting, and I'm just not used to seeing "condensed" code like this:
<?php if( $this->isEnabledViewSwitcher() ): ?>
<p class="view-mode">
<?php $_modes = $this->getModes(); ?>
<?php if($_modes && count($_modes)>1): ?>
<label><?php echo $this->__('View as') ?>:</label>
<?php foreach ($this->getModes() as $_code=>$_label): ?>
<?php if($this->isModeActive($_code)): ?>
<strong title="<?php echo $_label ?>" class="<?php echo strtolower($_code); ?>"><?php echo $_label ?></strong>
<?php else: ?>
<?php echo $_label ?>
<?php endif; ?>
<?php endforeach; ?>
<?php endif; ?>
</p>
<?php endif; ?>
I used to use the curly braces but now a days I prefer to use this short-hand alternative syntax because of code readability and accessibility.
Personally I prefer making it in two seperate sections but within the same PHP like:
<?php
if (question1) { $variable_1 = somehtml; }
else { $variable_1 = someotherhtml; }
if (question2) {
$variable_2 = somehtml2;
}
else {
$variable_2 = someotherhtml2;
}
etc.
$output=<<<HERE
htmlhtmlhtml$variable1htmlhtmlhtml$varianble2htmletcetcetc
HERE;
echo $output;
?>
But maybe it is slower?
I think it's a matter of preference. I personally use:
if($something){
$execute_something;
}
I used to use curly brackets for "if, else" conditions. However, I found "if(xxx): endif;" is more semantic if the code is heavily wrapped and easier to read in any editors.
Of course, lots editors are capable of recognise and highlight chunks of code when curly brackets are selected. Some also do well on "if(xxx): endif" pair (eg, NetBeans)
Personally, I would recommend "if(xxx): endif", but for small condition check (eg, only one line of code), there are not much differences.
I feel that none of the preexisting answers fully identify the answer here, so I'm going to articulate my own perspective. Functionally, the two methods are the same. If the programer is familiar with other languages following C syntax, then they will likely feel more comfortable with the braces, or else if php is the first language that they're learning, they will feel more comfortable with the if endif syntax, since it seems closer to regular language.
If you're a really serious programmer and need to get things done fast, then I do believe that the curly brace syntax is superior because it saves time typing
if(/*condition*/){
/*body*/
}
compared to
if(/*condition*/):
/*body*/
endif;
This is especially true with other loops, say, a foreach where you would end up typing an extra 10 chars. With braces, you just need to type two characters, but for the keyword based syntax you have to type a whole extra keyword for every loop and conditional statement.

Advise on simplifying a PHP statement

I am new to PHP and am coding a template file for a Joomla K2 item layout.
I have an 'extra field' $extrafields[15] configured which outputs as "Yes", "No" or "". $extrafields[16] is a text string.
I have this code, which works but would appriciate advice on how to simplify it, as I know it is probably a bit crude!
if (!empty($extrafields[15])):
if ($extrafields[15] == "Yes") {
echo "<span class=sgl-bold>Sponsored by: </span>";
}
if ($extrafields[15] == "Yes"):
if (!empty($extrafields[16])):
echo $extrafields[16];
endif;
echo "<br>";
endif;
endif;
I'd be inclined to do something like this:
if(!empty($extrafields[15]) && !empty($extrafields[16])){
if($extrafields[15] == "Yes"){
echo "<span class=sgl-bold>Sponsored by: </span>";
echo $extrafields[16];
echo "<br>";
} //endif not empty
} //endif yes
You can make your code more concise with just some simple tweaks:
Get rid of redundant if-clauses where possible,
combine if-clause conditions where it makes sense, and
don't use the alternative syntax for your control structures to cut down noise.
The following snippet preserves the same functionality than your original attempt but is imho more understandable.
if (!empty($extrafields[15]) && 'Yes' === $extrafields[15]) {
echo '<span class=sgl-bold>Sponsored by: </span>';
if (!empty($extrafields[16])) {
echo $extrafields[16];
}
echo '<br>';
}
That said, judging from the context, you probably want to go with the solution BigScar posted here.
To make this snippet even more understandable, you should consider working on the data structure (though I assume that this is something forced upon you by Joomla):
instead of a values in a numeric array like $extrafields[16] use speaking variable names like $showSponsor or the likes, and
instead of the string values of 'Yes', 'No' and '' use boolean values true, false and null.
Remember:
There are only two hard things in Computer Science: cache invalidation and naming things.
if (#$extrafields[15] == "Yes") {
echo "<span class=sgl-bold>Sponsored by: </span>";
echo #$extrafields[16];
echo "<br>";
}

PHP - if something is equal to something then echo something

I'm quite new to PHP now that I've started working with wordpress.
I'm trying to get something to work by using 'if'
Essentialy what I'm wanting to do is
If the status is equal to Open then return Link
If the status is not equal to Open then return Link
Here's what I think would work:
<?php
if ($status) == (open) {
echo "id=flashing"
}
?>
Obviosuly, I'm assuming this doesn't work but what I'm wanting to do is create a link
Any help?
This is a really basic PHP syntax question; please read some documentation, and look at some examples before asking for help with every piece of code you write.
There is a comprehensive online manual for PHP, with many examples. It is available in multiple translations, in case English is not your first language.
Things you have wrong in your example, with links to relevant pages of the manual:
no semi-colon to end the statement
no quotes around the string open
brackets in the wrong place in the if statement
The text of your question also confuses return and echo, which have very different meanings.
Does this help?
if ($status == 'open') {
echo 'Link';
} else {
echo '<a href="#" >Link</a>';
}
Just use the following code:
<?php
if ($status == 'Open') {
echo 'Link';
}
else {
echo '<a href="#" >Link</a>';
}
?>
<?php
if ($status == 'open')
{
echo 'Link';
}
else
{
echo '<a href="link" >Link</a>';
}
?>
Assuming Open is a string, it can be written like this (alternatively to the other answers):
echo '<a href="#" '.(($status == 'Open') ? 'id="flashing"':'').'>Link</a>';

Displaying an item depending on user login

This is the situation:
I have a list of items, and one of LI is:
echo '<li>Link</li>';
Now, I want to make an if statement here - if user is logged in, give home.php, else give index.php - but I'm kinda lost in all those "s and 's and .s so I'm asking for your help
This code won't do :/
echo '<li>Link</li>';
Also, I know I could do it with this code, but I want to finally get those dots and stuff
if ($logged == 0)
{
echo '<li>Link</li>';
}
else
{
echo '<li>Link</li>';
}
<?php echo '<li>Link</li>'; ?>
If you are after a short and concise solution try this:
<li>Link</li>
This is called a ternary operator. If $logged evaluates to true it will print 'home.php', otherwise it will print 'index.php'.
Here's an equivalent in standard if-else notation:
<li>Link</li>
You cannot use if's and echo's in echo parameters.
echo '<li>Link</li>';

Categories