Web Programming TutorialsConditionals and Regular Expressions in PHP

Conditionals and Regular Expressions in PHP

We learned functions in the last session. Today we are going to learn conditional statements and some regular expressions in this Conditionals and Regular Expressions tutorial.

Let us start with Conditional Statements.

  1. Create a new folder named Conditionals in htdocs folder in the xampp folder in C drive.
  2. Open a new notepad++ document and save it as index.php in the newly created Conditionals folder.
  3. We can embed PHP in HTML also, so let us write the following HTML code first:
  4. <!DOCTYPE html>
    <html>
    <head>
    <title>PHP Conditionals</title>
    </head>
    <body>
    </body>
    </html>
    
    • The page when opened in browser using localhost/Conditionals address in the address bar of the browser will look like this:
    • initial_output
      fig 1

  5. If statement:
    • If conditional statement is used to check whether a given condition is true or false.
    • If the given condition is satisfied, if statement returns true otherwise it returns false.
    • Write the following code in the body section of index.php page to demonstrate the if statement:
    • <?php
       $x=5;
       if($x>2)
       {
         echo $x." is greater than 2";
       }
      ?>
      
    • Here, we have assigned a value 5 to variable $x.
    • Condition $x>2 is checked in if statement.
    • If this condition evaluates to true, the statement in the curly braces will be executed.
    • The output is shown below:
    • if_statement_output
      fig 2

    • Now just change the value of variable $x from 5 to some other value less than 2 say 1.
    • When you reload the browser you will see that no output is seen.
    • This is because if block executes only when the condition is true; but we need to handle the situation even if the condition evaluates to false.
    • For this else part is used.
  6. If-else statement:
    • If the condition in if statement evaluates to false, else block of if-else statement is executed.
    • Write the following code in the body section of the page to demonstrate if-else statement.
    • <?php
       $x=1;
       if($x>2)
       {
         echo $x." is greater than 2";
       }
       else
       {
         echo $x." is NOT greater than 2";
       }
      ?>
      
    • Here, we see that variable $x has been assigned value 1.
    • The condition $x>2 in if statement will not be satisfied with value 1. So as the condition evaluates to false, else part of the statement will be executed.
    • The output is shown below:
    • if_else_statement_output
      fig 3

  7. Multiple conditions in the if statement:
    • We can use multiple conditions in if statement using logical operators such as logical AND (&&), logical OR (||) and logical Not (!).
    • Let us see an example using logical AND operator. Write the following code in the body section of the page:
    • <?php
      $x=4;
       if($x>2 && $x<10)
       {
         echo $x." is greater than 2 and less than 10.";
       }
      ?>
      
    • Here, we have assigned value 4 to variable $x.
    • Next we have checked 2 conditions $x>2 and $x<10 with a logical AND operator which insists that both the conditions should be true.
    • If and only if both the conditions are true, if block will be executed.
    • So the output is shown below:
    • multiple_conditions_in_if_block_output
      fig 4

  8. If – elseif statement:
    • If we want to check more than one condition, we can use if-elseif statement. It is also called if-elseif ladder.
    • Let us see an example. Write the following code in body section of the page:
    • <?php
      $x=4;
      if($x==10) 
      {
      	echo $x." is 10.";
      }
      elseif($x==2)
      {
      	echo $x." is 2.";
      }
      else
      {
      	echo $x." is not 10 or 2.";
      }
      ?>
      
    • In the above statements, a condition is checked in if statement first and if this condition evaluates to false then the next condition in the following elseif statement is checked.
    • This cycle continues till the condition does not evaluate to true.
    • If no condition is true then the statements in the else part are executed.
    • In the if-elseif statement of PHP the keyword elseif have no space in between.
    • In the above code $x variable is assigned value 4.
    • Then condition $x==10 in if statement is checked. This condition evaluates to false since 4 is not equal to 10.
    • Then next condition $x==2 in the elseif statement is checked. This condition also evaluates to false since 4 is not equal to 2.
    • So the statements in the else part are executed.
    • The output is shown below:
    • if_elseif_statement_output
      fig 5

    • If now you change the value of variable $x to 2 or 10, you will get different output.
    • Just change the value of variable $x to 2 and see the output.
    • Output is shown below:
    • if_elseif_changed_output
      fig 6

  9. Switch-case statement:
    • Switch-case statement is similar to if-elseif statement used to check multiple conditions.
    • Syntax of switch case statement is :
    • switch(variable/expression)
      {
      	case value 1: statement(s);
      		          break;	
                case value 2: statement(s);
      		          break;	
                case value n: statement(s);
      		          break;	
               default: statement(s);
                            break;
      }
      
    • We need to pass a variable or an expression whose value is to be matched with the case value.
    • Once the value passed in switch is matched with the case value, the statements inside that particular case are executed.
    • If no case value is matched then the statements of the default case are executed.
    • Write the following code of switch case in the body section of the page:
    • <?php
      $x=3;
      switch($x) 
      {
      	case 2: echo $x." matched 2";
      	        break;
      	case 3: echo $x." matched 3";
      			break;
      	default:echo $x." does not match 2 or 3";
      	        break;
      }
      ?>
      
    • Here, variable $x is assigned value 3 which is passed in the switch statement.
    • The value 3 in $x variable does not match with case 2, hence control goes to the next case i.e. case 3. Here the value in variable and the case value both are equal so the statements inside case 3 are executed.
    • The break statement is used to terminate and bring the control outside the switch block.
    • The output is shown below:
    • switch_case_output
      fig 7

    • Now change the value of $x to 5. You will get the output as 5 does not match 2 or 3.

    In this way we learned conditional statements, now we will go for Regular Expressions.

  10. Regular Expressions:
    • Regular expression is used to match something against something else.
    • They enable us to search patterns within a string and extract matches flexibly and precisely.
    • Some of the regular expressions and what will it match is shown in the table below:
    • Regular Expression Will match..
      foo The string “foo”
      ^foo “foo” at the start of a string
      foo$ “foo” at the end of a string
      ^foo$ “foo” when it is alone on a string
      [abc] a,b or c
      [a-z] Any lowercase letter
      [^A-Z] Any character that is not a uppercase letter
      (gif|jpg) Matches either “gif” or “jpeg”
      [a-z]+ One or more lower case letters
      [0-9.-] ?ny number, dot, or minus sign
      ^[a-zA-Z0-9_]{1,}$ Any word of at least one letter, number or _
      ([wx])([yz]) wy, wz, xy, or xz
      [^A-Za-z0-9] Any symbol (not a number or a letter)
      ([A-Z]{3}|[0-9]{4}) Matches three letters or four numbers
    • Let us try some examples of regular expressions.
    • There is a method called preg_match() used to match patters.
    • Syntax of preg_match() method is as follows:
    • preg_match(“/match string/”,”original string”,$matches)
    • In the syntax above, match string is the string to be matched with the original string. This match string is written between forward slashes.
    • $matches is an array that stores the match found in the string.
    • Write the following code in the body section of the page:
    • <?php
      if(preg_match("/ell/","Hello World",$matches))
      {
      	echo "Match was found<br/>";
      	echo $matches[0];
      }
      ?>
      
    • Here, preg_match() method is used in the if statement.
    • We are trying to search “ell” in the string “Hello World”.
    • If this string is found in the original string then it is stored in the array $matches passed as a third parameter of preg_match() method.
    • The output is shown below:
    • fig 8

  11. Search for a string at the beginning of the given string:
    • Now put a caret symbol(^) before ell and remove ‘H’ from the string “Hello World” in the above code as shown below:
    • <?php
      if(preg_match("/^ell/","ello World",$matches))
      {
      	echo "Match was found<br/>";
      	echo $matches[0];
      }
      ?>
      
    • The caret symbol preceding a string indicates that the string should be matched at the beginning of the original string.
    • In the above given code we have preceded ell with the caret symbol and the original string is ello World.
    • Since now the ell is at the beginning of the string it will match.
    • If the original string would have been Hello World then the ell would not have been matched because we required ell to be at the beginning.
    • The output is shown below:
    • beginning_match_output
      fig 9

    • Now try to search Hello at the beginning of the string Hello World using the code as follows:
    • <?php
      if(preg_match("/^Hello/","Hello World",$matches))
      {
      	echo "Match was found<br/>";
      	echo $matches[0];
      }
      ?>
      
    • You will find the match because Hello is at the starting of the string.
  12. Search for a string at the end of the given string:
    • To search for a string at the end of another string we need to put a dollar symbol ($) after the string to be searched.
    • Write the following code in the body section of the page:
    • <?php
      if(preg_match("/Hello$/","Hello World",$matches))
      {
      	echo "Match was found<br/>";
      	echo $matches[0];
      }
      else
      {
      	echo "No match found<br/>";
      }
      ?>
      
    • Here, in the above code we have put dollar symbol ($) after the string Hello. This indicates that the string Hello should be at the end of the string Hello World.
    • But since the string Hello is not at the end of Hello World, the match fails. Hence we don’t get any output.
    • Since condition in if statement has been failed, else block statement is executed and the following output is obtained:
    • match_at_end_output
      fig 10

    • Now if you remove World from the original string in the above code, you will get the output as match found because now there is only one word Hello in the original string.
  13. Searching for a string which is at the start as well as at the end:
    • When we want to search a string in a given string, the regular expression we use is put caret symbol (^) before and dollar symbol ($) after the string to be searched.
    • The following code demonstrates the regular expression for the same:
    • <?php
      if(preg_match("/^Hello$/","Hello",$matches))
      {
      	echo "Match was found<br/>";
      	echo $matches[0];
      }
      ?>
      
    • In the above code, we want to search for a string Hello at the start as well as end of the original string.
    • The original string is Hello. So we will get the match as there is only single word Hello in the original string.
    • The output is shown below:
    • start_and_end_match_rg_output
      fig 11

  14. Search for a given alphabet in a string:
    • To search for some alphabets in a string we need to use [abc] regular expression.
    • Write the following code in the body section of the page:
    • <?php
      if(preg_match("/[abc]/","Hello",$matches))
      {
      	echo "Match was found<br/>";
      	echo $matches[0];
      }
      ?>
      
    • The [abc] regular expression will search for the alphabets a, b and c in the string Hello.
    • But as there is no a, b or c alphabets in the string Hello, we will get no output.
    • But if instead of [abc] we use [Hbc], we will get the following output.
    • alphabet_match_rg_output
      fig 12

    • If we want a match which is not case sensitive, we should use i.For example see the following code:
    • <?php
      if(preg_match("/[hbc]/i","Hello",$matches))
      {
      	echo "Match was found<br/>";
      	echo $matches[0];
      }
      ?>
      
    • Here, we have capital H in the string Hello. But in regular expression we have used small h. To avoid considering case and make a match we need to use i at the end of the regular expression.
    • The output will be the same as shown in fig 12.

    In this way you can use different regular expressions listed in a table above for matching.

Thus we learned the conditional statements and some of the regular expressions in this Conditionals and Regular Expressions tutorial.

Previous articlePHP Functions
Next articleJavascript and Jquery Summary

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -