PHP if...else statement confusion - php

This is my first project digging into PHP and mySQL databases, and it's been a steep learning curve so far. I'm near the end of a Wordpress project and could use some help on if...else statements, which have been stumping me for a while. It uses custom fields.
Essentially I need the below flow, where "c01-sp-a" is a one word text variable and "c01-sp-v" is a number. I put variables in [] to clarify:
if ([c01-sp-a] = null)
[text of c01-sp-v]
else
[text of c01-sp-v]
I'd have to repeat this a few times, but I'd imagine having a good example for me would get me going.
Thanks!

You mean like this?
if ($c01_sp_a == null) {
echo $c01_sp_v;
} else {
echo ''.$c01_sp_v'.';
}

your variable can not contain '-' , you have to change your variable names ( i assume that variables are c01_sp_a and $c01_sp_v
if ($c01_sp_a == null)
echo $c01_sp_a;
else
<?php echo $c01_sp_v;?>

Related

Comparison complexity from left to right [duplicate]

This is a question that is bugging me for a long time and can't find any answer...
Noticed it's used quite a lot by Zend Framework Developers,
What is the difference between following 2 "if" statements? :
if (null === $this->user) { ... }
if ($this->user === null) { ... }
To me the first one looks kinda odd ;]
Thanks for answer.
This is not a difference for the way your script works, it's just a coding standard, a recommendation
The reason why it is recommended to use it this way:
if (null == $this->user)
is the fact that if you mistype and write = instead of == you will get an error, while
($this->user = null)
instead of
($this->user == null)
works but causes weird bugs (assignment and the final value is evaluated as bool instead of comparison)
and I guess it just extended as a habit to the strict comparison operator (===)
Update: since I see that there's still some activity on this thread even 3 years after I posted the answer I figured I would add something I forgot to mention. This type of notation is known as yoda conditions, you can read more about it on this wikipedia page for example.
It is a good practice for writing if statement. Consider this code:
if (10 == $var) {
echo 'true';
} else {
echo 'false';
}
If you forgot one equal sign:
if (10 = $var) { }
Then PHP will generate parse error, so you know you missed one = and you can fix it. But this code:
if ($var = 10) { }
will assign 10 to $var and always evaluates to true condition. Whatever the contents of $var, the code above will always echo 'true' and its very difficult to find this bug.
These are called yoda conditions.
The idea is that if you put the value first (such as false, null, true or anything short) it becomes easier for a person to scan the statement and quickly understand the intention of the condition.
Also, what mishu said :)
There is no difference in order when comparing values.
It may be easier for someone to read or write such a code, but to me it's the same as writing from right to left.
Such order of elements in comparison I think is meant to prevent accidental assignment in if statements.
The result will be the same, however, the second is logical.
You want to check if the variable is NULL, not if NULL is the variable...
The reason for doing it the other way around is described here:
http://umumble.com/blogs/Programming/321/
If you accidentally write:
if (null = $this->user) { ... }
you will get a syntax error.
If you accidentally write:
if ($this->user = null) { ... }
you will be searching for a reason of strange behavior of your application for a long time.

PHP - reversed order in if statement

This is a question that is bugging me for a long time and can't find any answer...
Noticed it's used quite a lot by Zend Framework Developers,
What is the difference between following 2 "if" statements? :
if (null === $this->user) { ... }
if ($this->user === null) { ... }
To me the first one looks kinda odd ;]
Thanks for answer.
This is not a difference for the way your script works, it's just a coding standard, a recommendation
The reason why it is recommended to use it this way:
if (null == $this->user)
is the fact that if you mistype and write = instead of == you will get an error, while
($this->user = null)
instead of
($this->user == null)
works but causes weird bugs (assignment and the final value is evaluated as bool instead of comparison)
and I guess it just extended as a habit to the strict comparison operator (===)
Update: since I see that there's still some activity on this thread even 3 years after I posted the answer I figured I would add something I forgot to mention. This type of notation is known as yoda conditions, you can read more about it on this wikipedia page for example.
It is a good practice for writing if statement. Consider this code:
if (10 == $var) {
echo 'true';
} else {
echo 'false';
}
If you forgot one equal sign:
if (10 = $var) { }
Then PHP will generate parse error, so you know you missed one = and you can fix it. But this code:
if ($var = 10) { }
will assign 10 to $var and always evaluates to true condition. Whatever the contents of $var, the code above will always echo 'true' and its very difficult to find this bug.
These are called yoda conditions.
The idea is that if you put the value first (such as false, null, true or anything short) it becomes easier for a person to scan the statement and quickly understand the intention of the condition.
Also, what mishu said :)
There is no difference in order when comparing values.
It may be easier for someone to read or write such a code, but to me it's the same as writing from right to left.
Such order of elements in comparison I think is meant to prevent accidental assignment in if statements.
The result will be the same, however, the second is logical.
You want to check if the variable is NULL, not if NULL is the variable...
The reason for doing it the other way around is described here:
http://umumble.com/blogs/Programming/321/
If you accidentally write:
if (null = $this->user) { ... }
you will get a syntax error.
If you accidentally write:
if ($this->user = null) { ... }
you will be searching for a reason of strange behavior of your application for a long time.

Do you see this breaking? any problems? simple php if elseif statement

I'm a total PHP newb, so there is probably a better way of outputting a row's class based on different variables.
Is this bad, and if it is why is it?
if ($variable1 > 0 && $variable2 != 2) {
echo "<tr class='variable1'>";
}
elseif ($variable2==2)
{
echo "<tr class='variable2'>";
}
else {
echo "<tr>";
}
The php code is syntactically correct, although the indentation seems to be messed up. The outputted HTML code is invalid though, since attributes values must be enclosed in double, not single quotes.
I'd also suggest a slight reordering:
if ($variable2 == 2) {
echo '<tr class="variable2">';
} elseif ($variable1 > 0) {
echo '<tr class="variable1">';
} else {
echo '<tr>';
}
You could put the if ($variable2==2) first and then you wouldn't need to negate it on the other if statement. Like this:
if ($variable2==2){
echo '<tr class="variable1">';
}elseif ($variable1 > 0) {
echo '<tr class="variable2">';
}else {
echo '<tr>';
}
Looks okay to me though, but it depends on the rest of the code really, you might be able to change the code slightly to make it easier to read but it looks pretty simple so, if it works, i'd keep it how it is.
I would write it like this:
$class_name = '';
if (2 == $variable2)
{
$class_name = 'variable2';
}
elseif ($variable1 > 0)
{
$class_name = 'variable1';
}
echo '<tr class="' , $class_name , '">';
notice that on the equality test I use the constant before the variable.. this is a habit so that if I miss one equal it would result in an error that I would be forced to correct it instead of a "strange" behavior
another thing is that I give the initial value to $class_name and that will be the default one
also I use apostrophes instead of quotation marks because it is faster (because the way you did it php will parse the string for variables)
and the last thing is that I echo multiple string.. that's also faster than concatenating 3 strings (
echo '<tr class="' , $class_name , '">';
and not echo
'<tr class="' . $class_name . '">';
)
Well you could start with
if ($variable2==2)
which would safe you the $variable2 != 2 if you continue with
elseif ($variable1 > 0)
but generally I see no mistake. Of course this depends on what else you want to do.
2 rules for you to learn how to program:
.1. DRY: Don't Repeat yourself.
if you have your tr tag typed 3 times, you can say for sure that's wrong.
.2. Separate business logic from presentation logic. Use templates for output. Prepare your data first and start output only if everything is ready.
So, first you have to define your variables
if ($variable2 == 2){
$class = "variable1";
}elseif ($variable1 > 0) {
$class = "variable2";
}else {
$class = "";
}
next you have to include a template and write native HTML in it, with as little PHP as possible:
<tr class="<?=$class?>">
Well, that is a really unfortunate approach at many levels, but I can tell you that even I started writing code the way you describe, only that was over 12 years ago.
I can also tell you that eventually mixing php with markup in the same files will come to bite you in the rear, and sooner than you think.
As with most things in life, getting it done faster and worrying about the rest later is a bad approch when developing in PHP.
A few pointers:
Try VERY hard to not mix PHP and HTML or other markup in the same file. Doing this will be more work when first developing but a LOT less work when changing and maintaining your code later.
PHP is an Object-oriented language. Learn how to use that to your advantage. Create libaries of your own classes for later reuse.
Use a good editor/IDE like NetBeans or Komode Editor - which are free.
The best resource for PHP info is the online PHP manual. Not only the manual pages are great, but the code snippets users contribute are full of little gems - and some glaring n00b errors too, but you will learn to filter that.
If you are new to programming in general, PLEASE do yourself a favor and get a book on programming. PHP is a very forgiving language and lets you get away with a lot of bad practices. As I said, those will come back sooner or later to get you.
After you gain some experience consider using a PHP framework, like CodeIgniter, CakePHP or ZendFramework. Try a few of them and choose the one that works for you.
Don't listen to people that tell you that PHP sucks. PHP is the most powerful programming language I have used, maybe excepting C and Prolog. The PHP array is the most powerful data structure I have encountered in any language - except linked lists in C ;-)
You CAN use PHP for every kind of programming task, including Windows and Linux server applications and full desktop graphical applications too. In fact, in my experience, PHP is faster than any dynamic language I have benchmarked it against - python, perl, ruby , tcl are all slower performing than PHP. But don't take my word for it, try it yourself :-)
A couple of links:
30+ PHP best practices for beginners
PHP bad programming practices
PHP OOP in full effect
PHP manual
echo ( ( $variable1 > 0 ) && ( $variable2 != 2 ) )
? "<tr class='variable1'>"
: ( $variable2 == 2 )
? "<tr class='variable2'>"
: "<tr>";

Most efficient php if structure

What runs faster?
Setting a default value and changing it-
$foo = "";
if($bar)
{
$foo = "someValue";
}
Or-
if($bar)
{
$foo = "someValue";
}
else
{
$foo = "";
}
You absolutely should not be bothered with performance of a single if statement.
Also, consider:
$foo = $bar ? "" : "someValue"
At a guess, the 2nd one "potentially". First one you're potentially setting 2 values. Second one you're definitely only setting one.
Its also a question though of code clarity. If you've got 2 alternatives (e.g turn left or right) then use the "else" statement. If you've got a 'normal' value vs a flag e.g http or https, then use the first one
EDIT: becose you valorize a variable in base to another one, the isset() statement is mandatory.. so the 'faster one' is the second way becose, as David said, yoo valorize the $foo var just one time.
Also consider the Anton suggestion to use the short if syntax (dont know if it speed up the execution)
P.s: if your goal is to speed up many if like that one, use the ' instead of ", becose the content inside "" is being evalutated by php (in case it contain a variable:

How to correctly format PHP 'IF ELSE' statements?

It's been a long running issue that I've come across in many-a-hot-and-steamy coding sessions.
One person codes this way another codes that way. So after much push and pull I'm curious...
Is there any correct way of phrasing a PHP 'IF ELSE' statement?
Personally I use the:
if ($variable == 'setvalue')
{
$variable = executefunctiononvariable($variable);
} else {
$variable = executedifferentfunctiononvariable($variable);
}
After many arguments though I've been presented with other options such as:
if ($variable == 'setvalue')
{
$variable = executefunctiononvariable($variable);
}
else
{
$variable = executedifferentfunctiononvariable($variable);
}
OR
if ($variable == 'setvalue')
$variable = executefunctiononvariable($variable);
else
$variable = executedifferentfunctiononvariable($variable);
OR
if ($variable == 'setvalue') {
$variable = executefunctiononvariable($variable);
} else {
$variable = executedifferentfunctiononvariable($variable);
}
I personally format my if/else like the last one:
if ($variable == 'setvalue') {
$variable = executefunctiononvariable($variable);
} else {
$variable = executedifferentfunctiononvariable($variable);
}
Your version is kind a mixture of 1 and 3, in my mind.
I have also worked with coders that do all of them and have never heard of a standard one.
The php website uses the last one: http://ca2.php.net/manual/en/control-structures.elseif.php
I also use the second example in some cases when the if statement will always be very short. If there's ever a possibiltiy of it getting longer (more than 1 line each) I'll do #1. I try to avoid #2 when possible cause it's hard to add the {} later.
I use the last one:
if ($variable == 'setvalue') {
$variable = executefunctiononvariable($variable);
} else {
$variable = executedifferentfunctiononvariable($variable);
}
That being said, it is pretty unimportant which one you go with, just make sure you are consistent.
The Right Way is to follow your project's coding standard. If you don't have one, adopt one from PHP-FIG, Zend, Symfony, etc.
This form appears very popular:
if (condition) {
statements
} else {
statements
}
For variable assignment I'll use a ternary only if the statement can fit legibly on one line:
$variable = !empty($foo) ? $foo : 'default';
Update: I've removed the bit about a multi-line ternary statements as I no longer consider this a wise practice.
I personnally prefer:
if(something){
doSomething();
}
elseif(somethingElse){
doSomethingElse();
}
else{
doAnotherThing();
}
Don't forget about
if (expression):
// code goes here
elseif (another expression):
// code goes here
else:
// code goes here
endif;
I personally like this structure when I'm cooking some tag soup.
The most important thing is that the programmers working on a project pretty much adhere to the same coding guidelines. So have a meeting and pick one or the other, and then stick with it.
I used to do (2) all the time but got it beaten out of me from Java programming as Sun's coding conventions use (4). So now I'm pretty used to (4). I've been doing a bit of C# lately and it seems to use (2) by default (sigh, here we go again).
In PHP from habit I do (4) but (2) is fine too. I don't like (1) at all.
And (3) is dangerous. Personally I think braces should be required by the syntax of the langauge even if its just for one statement. Saves you getting into trouble. I think that's how Perl does it from memory.
What I also hate is when people do this:
if (something) {
// do something
}
else if (something else) {
}
That one drives me batty. So I only find (2) and (4) acceptable. I don't care which one it is, as long as it's done consistently, preferably within the conventions for the language.
There is no right or wrong way, it is an opinion. Personally, I like the last one best (1TBS???). I never use the one without braces, I consider it bad style in general.
The only people that can really answer this question for you are the other people that are going to work on the code. It is important that everone agrees to a coding standard. Which standard you choose is less important than the fact that everyone uses it.
The PEAR coding standard is the PHP coding standard. I would recommend to get used to it as you will find it in other projects such as Zend, Doctrine, Symfony, Horde and many, many more.
http://framework.zend.com/manual/en/coding-standard.coding-style.html#coding-standard.coding-style.control-statements.if-else-elseif
In short, the is no correct way of doing. As long as it works, whatever you feel is the best, you can use. You should pick one and then stick to it, it will make your code easier to recognise.
The only thing is, if you don't include the "{" character you are limited to one expression or function.
Also, if you are only looking to define variables you can use the following code:
$variable = (CONDITIONAL STATEMENT) ? "It was true" : "It was false";
At my company we use:
if ($variable == 'setvalue')
{
$variable = executefunctiononvariable($variable);
}
else
{
$variable = executedifferentfunctiononvariable($variable);
}
I doesn't really matter aslong as there is a standard
Really to me... it just doesn't matter. I believe you should be able to read either way without issues. Does it really matter if the curly brace is on a new line or not? Does it really matter if there's a space after the closing parenthesis or not?
As long as the code is done in a such way that there's been at least an attempt at making it readable, I really just don't care.
Is there a correct way? Well if there was, then why do we have options of doing it differently?

Categories