PHP Doku:: if - control-structures.if.html

Verlauf / Chronik / History: (1) anzeigen

Sie sind hier:
Doku-StartseitePHP-HandbuchSprachreferenzKontrollstrukturenif

Ein Service von Reinhard Neidl - Webprogrammierung.

Kontrollstrukturen

<<Einführung

else>>

if

Das if-Konstrukt ist eines der wichtigsten Features vieler Programmiersprachen, so auch in PHP, denn es ermöglicht die bedingte Ausführung von Kodefragmenten. PHP bietet eine if-Anweisung die der in C ähnelt:

if (expression)
  statement

expression wird wie im Abschnitt über Ausdrücke beschrieben zu einem boolschen Wahrheitswert ausgewertet. Evaluiert expression zu TRUE so wird statement von PHP ausgeführt, anderenfalls wird es ignoriert. Weitere Informationen dazu welche Werte als TRUE oder FALSE ausgewertet werden können Sie im Abschnitt 'Umwandlung zu boolean'.

Das folgende Beispiel würde a ist größer als b ausgeben wenn $a größer als $b ist:

<?php
if ($a $b)
  echo 
"a ist größer als b";
?>

Oft werden Sie mehr als eine Anweisung bedingt ausführen wollen. Dazu ist es natürlich nicht möglich jede Anweisung mit einer eigenen if-Anweisung zu versehen. Sie können statt dessen mehrere Anweisung zu einer Anweisungsgruppe zusammenfassen. So würde z.B. der folgende Programmcode a ist größer als b ausgeben und den Wert von $a an $b zuweisen:

<?php
if ($a $b) {
  echo 
"a ist größer als b";
  
$b $a;
}
?>

If-Anweisungen können beliebig oft ineinander verschachtelt werden und bieten Ihnen so vollständige Flexibilität für die bedingte Ausführung der verschiedenen Teile Ihres Programs.


16 BenutzerBeiträge:
- Beiträge aktualisieren...
techguy14 at gmail dot com
6.01.2011 22:39
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!
admin at leonard !spam challis dot com
22.11.2010 13:41
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".
Rudi
14.09.2010 22:14
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
austinderrick2 at gmail dot com
3.10.2009 13:50
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
===================================
jm+phpweb at roth dot lu
28.08.2009 23:25
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
strata_ranger at hotmail dot com
5.04.2009 3:13
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);
?>
Anonymous
2.04.2009 14:32
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 !
contact at bsorin dot romania
7.03.2009 17:28
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.
Anonymous
28.09.2008 14:03
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 
?>
john
25.09.2008 5:24
@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.
Wiseguy
28.08.2008 16:22
RE: chrislabricole at yahoo dot fr on 09-Aug-2008 05:53

You're referring to the ternary operator.

http://php.net/manual/en/language.operators.comparison.php
jchau at bu dot edu
14.08.2008 19:50
RE: henryk dot kwak at gmail dot com's comment from 04-May-2008 05:01

I think you made a mistake.

For maximum efficiency, assuming each expression requires the same amount of processing, the expression that is least likely to be true should come first for expressions connected by && (and).  This will reduce the probability that later expressions will need to be evaluated. 

The opposite is true for || (or).  If the most likely expression comes first, then the probability of needing to evaluate later expressions is reduced.
chrislabricole at yahoo dot fr
10.08.2008 2:53
You can do IF with this pattern :
<?php
$var
= TRUE;
echo
$var==TRUE ? 'TRUE' : 'FALSE'; // get TRUE
echo $var==FALSE ? 'TRUE' : 'FALSE'; // get FALSE
?>
henryk dot kwak at gmail dot com
5.05.2008 2:01
When you use if command with many condidions like
if ( expr1 && expr2 && expr3 && etc. )
it is more effective to put expressions in special order
Firstly you should put that, which has the biggest
probability to occur.
This is because PHP checks each condition in order from left to right and it takes some time to check each condition.
grawity at gmail dot com
10.03.2008 12:41
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.
redrobinuk at aol dot com
9.01.2008 11:54
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...



PHP Powered Diese Seite bei php.net
The PHP manual text and comments are covered by the Creative Commons Attribution 3.0 License © the PHP Documentation Group - Impressum - mail("TO:Reinhard Neidl",...)