Bootstrap FreeKB - PHP - if elseif else statements
PHP - if elseif else statements

Updated:   |  PHP articles

An if elsif statement in PHP has the following structure.

if (comparison) {
  --do something--
  }
elseif (comparison) {
  --do something--
  }
else {
  --do something
}

 

For example.

if ($foo == 10) {
    echo "foo equals 10.";
} 
elseif ($foo == 20) {
    echo "foo equals 20.";
} 
else {
    echo "foo does not equal 10 or 20.";
}

 

Following are common if statements.

Equals string

Equals boolean

if ($foo == "Hello World")

if ($foo == true)

Does not equal string

Does not equal boolean

if ($foo != "Hello World")

if ($foo != true)

Greater than

tbd

Less than

tbd

Greater than or equal to

tbd

Less than or equal to

tbd

If file or directory exists

if (file_exists('/path/to/foo.txt'))

If URL exists see http://www.freekb.net/Article?id=3525
If variable is defined if (isset($foo))
If variable is not defined if (!isset($foo))
If variable is empty (null) if (empty($foo))
If variable is not empty (not null) if (!empty($foo))
If array is empty (null) if (empty($array))
If array is not empty (not null) if (!empty($array))
If variable contains

if (preg_match('/hello|world/i', $foo))

If variable does not contain if (!preg_match('/hello|world/i', $foo))
If array contains if (in_array("bar", $foo ))
If array does not contain if (!in_array("bar", $foo ))
If array contains exact match tbd
If array does not contain exact match tbd
If hash contains tbd
If hash does not contain tbd
If file contains / does not contain tbd
If string begins with if (preg_match('/^(hello|world)/i', $foo))
If string does not begin with if (!preg_match('/^(hello|world)/i', $foo))
If string ends with if (preg_match('/(hello|world)$/i', $foo))
If string does not end with if (!preg_match('/(hello|world)$/i', $foo))

 

 


Multiple conditions

Here is one way to handle multiple conditions.

if (($foo == "Hello") or ($foo == "World")) {
  echo "foo equals Hello or World";
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 18193f in the box below so that we can be sure you are a human.