SunshinePHP Developer Conference 2015

if

(PHP 4, PHP 5)

The if construct is one of the most important features of many languages, PHP included. It allows for conditional execution of code fragments. PHP features an if structure that is similar to that of C:

if (expr)
  statement

As described in the section about expressions, expression is evaluated to its Boolean value. If expression evaluates to TRUE, PHP will execute statement, and if it evaluates to FALSE - it'll ignore it. More information about what values evaluate to FALSE can be found in the 'Converting to boolean' section.

The following example would display a is bigger than b if $a is bigger than $b:

<?php
if ($a $b)
  echo 
"a is bigger than b";
?>

Often you'd want to have more than one statement to be executed conditionally. Of course, there's no need to wrap each statement with an if clause. Instead, you can group several statements into a statement group. For example, this code would display a is bigger than b if $a is bigger than $b, and would then assign the value of $a into $b:

<?php
if ($a $b) {
  echo 
"a is bigger than b";
  
$b $a;
}
?>

If statements can be nested infinitely within other if statements, which provides you with complete flexibility for conditional execution of the various parts of your program.

add a note add a note

User Contributed Notes 21 notes

up
22
robk
1 year ago
easy way to execute conditional html / javascript / css / other language code with php if else:

<?php if (condition): ?>

html code to run if condition is true

<?php else: ?>

html code to run if condition is false

<?php endif ?>
up
11
Anonymous
5 years ago
If you need to do something when a function return FALSE and nothing when it return TRUE you can do it like that :
<?php
function call()
{
return
FALSE;
}

if(
call()==TRUE) // or if(call())
{
// nothing to do
}
else
{
// do something here
}
?>

You can also write it like this :
<?php
if(!call()==TRUE) // or if(!call())
{
// do something here
}
// here '!' will invert 'FALSE' (from call()) into 'TRUE'
?>
/!\ WARNING /!\
The '!' only work with booleans !
Check http://fr.php.net/manual/en/language.types.boolean.php to know if you can use '!'

If you want to compare two strings and use '!' be careful how you use it !!!!
<?php
$string1
= "cake";
$string2 = "foo";

if(!
$string1==$string2)
{
echo
"cake is a lie";
}
//this will ALWAYS fail without exception because '!' is applied to $string1 and not to '$string1==$string2'

//to work, you have to do like this
if(!($string1==$string2))
{
echo
"cake is a lie";
}
//it will display 'cake is a lie' because ($string1==$string2) return FALSE and '!' will invert it into TRUE
?>
For array/float, it's the same !
up
2
Donny Nyamweya
3 years ago
In addition to the traditional syntax for if (condition) action;
I am fond of the ternary operator that does the same thing, but with fewer words and code to type:

(condition ? action_if_true: action_if_false;)

example

(x > y? 'Passed the test' : 'Failed the test')
up
3
chrislabricole at yahoo dot fr
6 years ago
You can do IF with this pattern :
<?php
$var
= TRUE;
echo
$var==TRUE ? 'TRUE' : 'FALSE'; // get TRUE
echo $var==FALSE ? 'TRUE' : 'FALSE'; // get FALSE
?>
up
1
ehsan at chavoshi dot com
2 years ago
You can use a simple if and echo structure :

$i==1 and print "i is 1"
is identical with
if ($i ==1)
  echo "i is 1";
up
1
Christian L.
3 years ago
An other way for controls is the ternary operator (see Comparison Operators) that can be used as follows:

<?php
$v
= 1;

$r = (1 == $v) ? 'Yes' : 'No'; // $r is set to 'Yes'
$r = (3 == $v) ? 'Yes' : 'No'; // $r is set to 'No'

echo (1 == $v) ? 'Yes' : 'No'; // 'Yes' will be printed

// and since PHP 5.3
$v = 'My Value';
$r = ($v) ?: 'No Value'; // $r is set to 'My Value' because $v is evaluated to TRUE

$v = '';
echo (
$v) ?: 'No Value'; // 'No Value' will be printed because $v is evaluated to FALSE
?>

Parentheses can be left out in all examples above.
up
1
sofwan at sofwan dot net
2 years ago
It seems that only numbers can be compared between them but actually an alphabet can be compare too. For example :

<?php
// Number comparison
 
$a="C";
 
$b="X";
  if (
$a<$b)
     {
    echo
$a."is smaller than".$b;
    }               
// Result : C is smaller than X
?>
up
0
blackcreeper97
2 days ago
SUBSCRIBE ME ON YOUTUBE NOW!!!!!
up
1
john
6 years ago
@henryk (and everybody):

You should put your arguments in order by *least* likely to be true. That way if php is going to be able to quit checking, it will happen sooner rather than later, and your script will run (what amounts to unnoticeably) faster.

At least, that makes the most sense to me, but I don't claim omniscience.
up
0
admin at leonard !spam challis dot com
3 years ago
When using if statements without the curly braces, remember than only one statement will be executed as part of that condition. If you want to place multiple statements you must use curly braces, and not just put them on the same line.

<?php

if (1==0) echo "Test 1."; echo "Test 2";

?>

Whereas some people would expect nothing to be displayed, this piece of code will show: "Test 2".
up
0
contact at bsorin dot romania
5 years ago
This has got the better part of my last 2 hours, so I'm putting it here, maybe it will save someone some time.

I had a

if (function1() && function2())

statement. Before returning true or false, function1() and function2() had to output some text. The trick is that, if function1() returns false, function2() is not called at all. It seems I should have known that, but it slipped my mind.
up
-2
techguy14 at gmail dot com
3 years ago
You can have 'nested' if statements withing a single if statement, using additional parenthesis.
For example, instead of having:

<?php
if( $a == 1 || $a == 2 ) {
    if(
$b == 3 || $b == 4 ) {
        if(
$c == 5 || $ d == 6 ) {
            
//Do something here.
       
}
    }
}
?>

You could just simply do this:

<?php
if( ($a==1 || $a==2) && ($b==3 || $b==4) && ($c==5 || $c==6) ) {
   
//do that something here.
}
?>

Hope this helps!
up
-2
redrobinuk at aol dot com
6 years ago
This is aimed at PHP beginners but many of us do this  Ocasionally...

When writing an if statement that compares two values, remember not to use a single = statement.

eg:
<?php
if ($a = $b)
     {
         print(
"something");
     }
?>
This will assign $a the value $b and output the statement.

To see if $a is exactly equal to $b (value not type) It should be:
<?php
    
if ($a == $b)
     {
         print(
"something");
     }
?>
Simple stuff but it can cause havok deep in classes/functions etc...
up
-2
grawity at gmail dot com
6 years ago
re: #80305

Again useful for newbies:

if you need to compare a variable with a value, instead of doing

<?php
if ($foo == 3) bar();
?>

do

<?php
if (3 == $foo) bar();
?>

this way, if you forget a =, it will become

<?php
if (3 = $foo) bar();
?>

and PHP will report an error.
up
-2
austinderrick2 at gmail dot com
5 years ago
As an added note to the guy below, in such a case, use the !== operator like this.

$nkey = array_search($needle, $haystack);

if ($nkey !== false) { ...

The !== and the === compare the "types". So, with this type of comparision, 0 is not the same as the FALSE returned by the array_search array when it can not find a match. :)

Quoted Text:

===================================
Be careful with stuff like

if ($nkey = array_search($needle, $haystack)) { ...

if the returned key is actually the key 0, then the if won't be executed
===================================
up
-3
Anonymous
6 years ago
Re : henryk dot kwak at gmail dot com
<?php function message($m)
{
echo
"$m <br />\r";
return
true;
}
$k=false;
if (
message("first")&& $k && message("second")){;}
// will show
//first
class
$k=true;
if (
message("first")&& $k && message("second")){;}
// will show
//first
//second 
?>
up
-3
m dot folkerts at sobit dot nl
8 months ago
What is the result of?

$a = 0;
$b = "any string";

if($a == $b) echo "true";
else echo "false";

result: true

this get's solved if you use === but still.
up
-6
strata_ranger at hotmail dot com
5 years ago
Although most programmers are aware of this already, if for whatever reason you need to 'break' out of an if() block (which, unlike switch() is not considered a looping structure) just wrap it in an appropriate looping structure, such as a do-while(false):

<?php
do if ($foo)
{
 
// Do something first...

  // Shall we continue with this block, or exit now?
 
if ($abort_if_block) break;

 
// Continue doing something...

} while (false);
?>
up
-10
Aldee Mativo
8 months ago
If you intend only a single line (one-way) conditional script, you can do the following:

empty($user) || $user->save();

if $user variable is empty, it will not execute $user->save(). Otherwise it will perform saving operation. In other words/form of expression, it can be expressed like this:

if(!empty($user))
    $user->save();
up
-14
Rudi
4 years ago
Note that safe type checking (using === and !== instead of == and !=) is in general somewhat faster. When you're using non-safe type checking and a conversion is really needed for checking, safe type checking is considerably faster.

===================================
Test (100,000,000 runs):
<?php
$start
= microtime(true);
for(
$i = 0; $i < 100000000; $i++)
    if(
5 == 10) {}
$end = microtime(true);
echo
"1: ".($end - $start)."<br />\n";
unset(
$start, $end);

$start = microtime(true);
for(
$i = 0; $i < 100000000; $i++)
    if(
'foobar' == 10) {}
$end = microtime(true);
echo
"2: ".($end - $start)."<br />\n";
unset(
$start, $end);

$start = microtime(true);
for(
$i = 0; $i < 100000000; $i++)
    if(
5 === 10) {}
$end = microtime(true);
echo
"3: ".($end - $start)."<br />\n";
unset(
$start, $end);

$start = microtime(true);
for(
$i = 0; $i < 100000000; $i++)
    if(
'foobar' === 10) {}
$end = microtime(true);
echo
"4: ".($end - $start)."<br />\n";
unset(
$start, $end);
?>

===================================
Result (depending on hardware configuration):
1: 16.779544115067
2: 21.305675029755
3: 16.345532178879
4: 15.991420030594
up
-21
jm+phpweb at roth dot lu
5 years ago
Be careful with stuff like

if ($nkey = array_search($needle, $haystack)) { ...

if the returned key is actually the key 0, then the if won't be executed
To Top