PHP Switch Statement

The PHP switch statement is almost similar to the if elseif else statements.

Syntax

 
switch (expression) {

case label1:

    Block of code // executes if expression = label1;

    break;

case label2:

    Block of code // executes if expression = label2;

    break;

default:

    Block of code // executes if expression value is different from all above labels;
}

The switch statement will execute the expression first and then compare its result with the defined label. If label matches with the expression result then it executes the block of statement defined in the specific label. The break statement will stop the execution of loop and starts the execution of block of code after the switch statement.

In the given below example, firstly current day is calculated. If current day is Sunday or Saturday then it will display the message accordingly. Otherwise, default label will be executed.

<?php
	$KH_CurrentDate = date('d-m-Y');
	$KH_CurrentDay = date("D", strtotime($KH_CurrentDate));
	switch($KH_CurrentDay) {
		case "sun":
			echo "Today is a holiday";
			break;            
		case "sat":
			echo "Today is a half-working day";
			break;
		default:
			echo "Today is a working day";
	}
?>

Download the code Run the code

PHP if elseif else statements

Very often, while writing the code, some decisions are required to perform certain actions. In PHP, you can use following decision making statements for the same.

  • if statement
  • if else statement
  • if elseif else statement
  • switch statement

The if statement

It executes the code for specific one condition.

Syntax

if (condition) {

// Block of code; // Executed only if condition is true

}

Example

<?php
	$KH_CurrentDate = date('d-m-Y');
	$KH_CurrentDay = date("D", strtotime($KH_CurrentDate));

	if ($KH_CurrentDay == "sun")
	  echo "Today is a holiday";
	if ($KH_CurrentDay != "sun")
	  echo "Today is not a holiday";
?>

Download the code Run the code

The if…else statement

It executes some set of statements if condition is true. Otherwise, execute another set of code if condition is false.

Syntax

if  (condition) {

Block of code; // Executes only if condition is true

}  else {

Block of code; // Executes only if condition is false

}

Example

<?php
	$KH_CurrentDate = date('d-m-Y');
	$KH_CurrentDay = date("D", strtotime($KH_CurrentDate));

	if ($KH_CurrentDay == "sun")
	  echo "Today is a holiday";
	else
	  echo "Today is a working day";
?>

Download the code Run the code

The if elseif else statement

It executes different set of statements depending on the conditions.

Syntax

if (condition) {

Block of code; // Executes only if condition is true

} elseif (condition) {

Block of code; // Executes only if above condition is false and this condition is true

} else {

Block of code; // Executes only if all above condition are false

}

Example

<?php
	$KH_CurrentDate = date('d-m-Y');
	$KH_CurrentDay = date("D", strtotime($KH_CurrentDate));

	if ($KH_CurrentDay == "sun")
	  echo "Today is a holiday";
	elseif ($KH_CurrentDay == "sat")
	  echo "Today is a half working day";
	else
	  echo "Today is a working day";
?>

Download the code Run the code

We will discuss the Switch statement in the next chapter.

PHP Operators

Operators operate on variables and produce calculated results such as additions or multiplications or comparisons. In PHP, following are operators are available.

  • Arithmetic Operators
  • Comparison Operators
  • Logical Operators
  • Assignment Operators

Let’s discuss each operator one by one.

Arithmetic operators

Operator Description
+ Adds two operands
Subtracts right operand from the left operand
* Multiplies two operands
/ Divides left operand by right operand
% Modulus operation (remainder of left operand divided by right operand)
++ Increment operand by one integer value
Decrement operand by one integer value

<?php
	$KH_Operand1 = 55;
	$KH_Operand2 = 15;
	 
	$KH_Result = $KH_Operand1 + $KH_Operand2;
	echo "Operand1 + Operand2 = $KH_Result <br/>";
	 
	$KH_Result = $KH_Operand1 - $KH_Operand2;
	echo "Operand1 - Operand2 = $KH_Result <br/>";
	 
	$KH_Result = $KH_Operand1 * $KH_Operand2;
	echo "Operand1 * Operand2 = $KH_Result <br/>";
	 
	$KH_Result = $KH_Operand1 / $KH_Operand2;
	echo "Operand1 / Operand2 = $KH_Result <br/>";
	 
	$KH_Result = $KH_Operand1 % $KH_Operand2;
	echo "Operand1 % Operand2 = $KH_Result <br/>";
	 
	$KH_Result = ++$KH_Operand1; 
	echo "++ Opearrtor1 = $KH_Result <br/>";
	 
	$KH_Result = --$KH_Operand2; 
	echo "-- Operand2 = $KH_Result <br/>";
?>

Download the code Run the code

Comparison Operators

Operator Description
== Condition is true only when value of two operands are same
!= Condition is true only when value of both operands is different
< Condition is true only when value of first operand is less than second operand
> Condition is true only when value of first operand is greater than second operand
<= Condition is true only when value of first operand is less than or equal to second operand
>= Condition is true only when value of first operand is greater than or equal to second operand

<?php
	$KH_Operand1 = 55;
	$KH_Operand2 = 15;

	if ($KH_Operand1 == $KH_Operand2) 
	  echo "Operand1 is equal to Operand2 <br/>";
	else
	  echo "Operand1 is not equal to Operand2 <br/>";

	if ($KH_Operand1 < $KH_Operand2) 
	  echo "Operand1 is less than Operand2 <br/>";
	else
	  echo "Operand1 is not less than Operand2 <br/>";

	if ($KH_Operand1 > $KH_Operand2) 
	  echo "Operand1 is greater than Operand2 <br/>";
	else
	  echo "Operand1 is not greater than Operand2 <br/>";

	if ($KH_Operand1 <= $KH_Operand2) 
	  echo "Operand1 is less or equal to Operand2 <br/>";
	else
	  echo "Operand1 is not less or equal to Operand2 <br/>";

	if ($KH_Operand1 >= $KH_Operand2) 
	  echo "Operand1 is greater or equal to Operand2 <br/>";
	else
	  echo "Operand1 is not greater or equal to Operand2 <br/>";

	if ($KH_Operand1 != $KH_Operand2) 
	  echo "Operand1 is not equal to Operand2 <br/>";
	else
	  echo "Operand1 is equal to Operand2 <br/>";
?>

Download the code Run the code

Logical Operators

Operator Description
and Condition is true only if the value of both operands is true
or Condition is true only if the value of either operands is true
&& Condition is true only if the value of both operands is true
|| Condition is true only if the value of either operands is true
! Condition is true only if the value of operand is false

<?php

	$KH_Operand1 = 55;
	$KH_Operand2 = 0;
	 
	if ($KH_Operand1 == 55 && $KH_Operand2 == 15) 
	  echo "Both operands are true <br/>";
	else
	  echo "Either of operands is false <br/>";

	$KH_Operand2 = 15;

	if ($KH_Operand1 and $KH_Operand2)
	  echo "Both operands are true <br/>";
	else
	  echo "Either of operands is false <br/>";
	 
	$KH_Operand1 = 55;
	$KH_Operand2 = 0;

	if ($KH_Operand1 || $KH_Operand2)
	  echo "Either of operands is true <br/>";
	else
	  echo "Both operands are false <br/>";

	$KH_Operand1 = 0;
	$KH_Operand2 = 0;

	if ($KH_Operand1 or $KH_Operand2)
	  echo "Either of operands is true <br/>";
	else
	  echo "Both operands are false <br/>";

	$KH_Operand1 = 55;
					  
	if (!$KH_Operand1)
	  echo "Operand is false <br/>";
	else
	  echo "Operand is true <br/>";
	 
	if (!$KH_Operand2)
	  echo "Operand2 is false <br/>";
	else
	  echo "Operand2 is true <br/>";
?>

Download the code Run the code

Assignment Operators

Operator Description
= Assign right side operand value to left side operand
+= First add the value of right operand to left side operand and then result is assigned to left operand
-= First subtract the value of right operand from left side operand and then result is assigned to left operand
*= First multiply the value of right operand with left side operand and then result is assigned to left operand
/= First divide the value of left operand with right side operator and then result is assigned to left operand
%= First take the modulus of two operands and then result is assigned to left operand

<?php

	$KH_Operand1 = 55;
	$KH_Operand2 = 15;

	$KH_Result = $KH_Operand1 + $KH_Operand2;   
	echo "Addtion Operation Result: $KH_Result <br/>"; // Output: Addtion Operation Result: 70 

	$KH_Result += $KH_Operand1;
	echo "Add AND Assigment Operation Result: $KH_Result <br/>"; // Output: Add AND Assigment Operation Result: 125 

	$KH_Result -= $KH_Operand1; 
	echo "Subtract AND Assignment Operation Result: $KH_Result <br/>"; // Output: Subtract AND Assignment Operation Result: 70 

	$KH_Result *= $KH_Operand1; 
	echo "Multiply AND Assignment Operation Result: $KH_Result <br/>"; // Output: Multiply AND Assignment Operation Result: 3850 

	$KH_Result /= $KH_Operand1; 
	echo "Division AND Assignment Operation Result: $KH_Result <br/>"; // Output: Division AND Assignment Operation Result: 70 

	$KH_Result %= $KH_Operand1; 
	echo "Modulus AND Assignment Operation Result: $KH_Result <br/>"; // Output: Modulus AND Assignment Operation Result: 15 
?>

Download the code Run the code

PHP Constants

In PHP, constant is an identifier which holds a constant value. The value of constant cannot be changed while executing the script.

Syntax

Constants are declared by using define() function.

define (name, value, case-insensitive)

Name and value are mandatory parameters. Whereas, case-insensitive is an optional parameter. Its default value is false.

Characteristics of constants

  • Constants do not require $ sign.
  • They start with an alphabet or underscore ( _ ) and contain alphanumeric characters
  • Constants are global and accessible in the entire script.
  • Constants cannot be re-assigned or undefined, once they are defined.
  • Constant names are conventionally defined in uppercase.

Valid and invalid constants identifiers

<?php
	// Valid constant names
	define("DATABASE", "Wordpress");
	define("DATABASE2", "Magento");
	define("DATABASE_SYMPHONY", "Symphony");

	// Invalid constant name
	define("3DATABASE", "Symphony");

	// Valid constant name, but do not suggest as PHP my use same name as magical constant in future, 
	// which may break your script.
	define("__DATABASE__", "Joomla");

	echo DATABASE . "<br>";
	echo DATABASE2 . "<br>";
	echo 3DATABASE . "<br>"; // This will generate an error
	echo __DATABASE__ . "<br>";
?>

Download the code Run the code

const keyword

Alternatively, constant variable can be defined using const keyword.

<?php
	const KH_NAME  = "John";
	echo "My name is " . KH_NAME;
?>

Download the code Run the code

constant () Function

It is used to retrieve the value of constant. It is helpful when you know the name of constant and want to retrieve its value.

<?php
	define("KH_NAME", "My name is John");
	echo constant("KH_NAME");
?>

Download the code Run the code

get_defined_constants() function

It will return the array of constants name and their values. It include the default constants as well as user defined constants.

<?php
	define("KH_DATABASE", "Wordpress");
	define("KH_USER", "John");
	const KH_PASSWORD = "password";

	echo "<pre>";
	print_r(get_defined_constants());
	echo "</pre>";
?>

Download the code Run the code

PHP Data Types

In PHP, a variable holds different values of various data types. Following data types are supported by PHP:

  • Integers
  • Strings
  • Doubles
  • Booleans
  • Arrays
  • Objects
  • Null
  • Resources

Integers

They are a non-decimal numbers and can be negative, zero and positive values. The range of integers is -2,147,483,648 to 2,147,483,647. Integers can be in three different formats: Hexadecimal (Base 16), Decimal (Base 10) and Octal (Base 8).

In the given below example, variables $KH_Number1 and $KH_Number2 are assigned an integer value. You can know the datatype of variable using var_dump function of PHP.

<?php
	$KH_Number1 = 3120;
	var_dump($KH_Number1);  

	$KH_Number2 = 451 + 98421;
	var_dump($KH_Number2);
?>

Download the code Run the code

Strings

They are sequences of the characters. String can be defined using single quote and double quote. Single quote will consider the string as it is, whereas, double quote can parse the variable and replace its value.

<?php
	$KH_Name = "John";
	$KH_DisaplyName1 = 'My name $KH_Name is not displayed here'; 
	$KH_DisaplyName2 = "My name is $KH_Name"; 

	echo $KH_DisaplyName1 . "<br>"; // Output: My name $KH_Name is not displayed here
	echo $KH_DisaplyName2 ;         // Output: My name is John
?>

Download the code Run the code

Doubles

They are numbers with decimal places like 461.45.

<?php
	$KH_Double = 945.12;
	var_dump ($KH_Double);
?>

Download the code Run the code

Booleans

They have likely two states either true or false. Booleans are frequently used in conditional testing with if statement.

<?php
	$KH_Knowphp = true; 
	if ($KH_Knowphp)
	  echo "I know PHP script";
	else
	  echo "I don't know PHP script";
?>

Download the code Run the code

null

It is a special data type which contains only one value: null. The variable of null data types means that variable is not assigned with any value. It is often used with isset() function.

<?php
	$KH_Name = null;
	if (!isset($KH_Name))
		echo "Variable does not contain value";
	else
		echo "Variable has the value of $KH_Name";
?>

Download the code Run the code

PHP Variables

A variable is used for holding information during the execution of PHP scripts. In PHP, variables are denoted with dollar sign ($) in the beginning. Unlike javascript or other languages, we don’t precede variable name with any qualifier such as int, char, var etc.

  • Value is assigned to variable by = operator. Variable will be on left side of operator and value at the right side.
  • A variable can be assigned many values at differents points of time but the variable holds the value of the most recent assignment
  • Variable can be declared before assignment but it is not mandatory. It will be created automatically at the time of assigning the value.
  • Variable is not required to declare its data type like in other programming languages.
  • PHP converts data type of variable automatically depending on its value.
  • Variable name is case-sensitive.

Output the value of variables

In PHP, echo or print statements are used to output the value of variable to the screen, which is usually a web page.

<?php
	$KH_Name = "John";
	echo "My name is : " . $KH_Name  . "<br>";
	print ("My name is :  $KH_Name");
?>

Download the code Run the code

Variable scope

Variable can be declared anywhere in the PHP script. However, the scope of variable varies depending on the position of its declaration. In PHP, there are three types of variable scope:

  • Local
  • Global
  • Static

Local scope

In the below example, variable $KH_Name is declared within function. It can be accessed within function only. The usage of variable outside the function will generate an error.

<?php
	function KH_DisplayMyName() {
		$KH_Name = "John"; // local scope
		echo "Display my name inside the function: $KH_Name<br>";
	} 

	KH_DisplayMyName();

	// Access of $KH_Name variable will display an error
	echo "Display my name outside the function: $KH_Name<br>";
?>

Download the code Run the code

Global scope

The global variable can be accessed through global keyword within the function. In the below example, global keyword is used before the variable $KH_Name.

<?php
	$KH_Name = "John"; // Global scope

	function KH_DisplayMyName() {
		global $KH_Name;
		echo "Display my name inside the function: $KH_Name<br>";
	} 

	KH_DisplayMyName();
	echo "Display my name outside the function: $KH_Name<br>";
?>

Download the code Run the code

Static scope

As soon as the execution of function is completed, the scope of all variables declared within the function ends and we lose their values as well. Sometimes, it is required to hold the value of local variable for further process. It can be achieved by using static keyword in front of the variable while declaring or assigning the values for the first time.

<?php
	function KH_DisplayCount() {
		static $KH_Count = 1;
		echo "Counter value : $KH_Count<br>";
		$KH_Count ++;
	} 

	KH_DisplayCount();  // Output: Counter value : 1
	KH_DisplayCount();  // Output: Counter value : 2
	KH_DisplayCount();  // Output: Counter value : 3
	KH_DisplayCount();  // Output: Counter value : 4
?>

Download the code Run the code

PHP Syntax

PHP script can be written anywhere inside a HTML document. It can be inserted between HTML or JavaScript tags.

PHP tags

The most commonly used PHP tag style starts with <?php and ends with ?>

<?php
// Block of PHP code
?>

Short-open tags

If you are using short-open tags then ensure short_open_tag is enabled and set to ON in configuration file php.ini.

<?
// Block of PHP code
?>

Comments in PHP code

Comments are used to describe the code, which is only intended to be read by human beings. Comments do not get compiled or executed. The purpose of comments is to help others understand or remind you later what has been implemented and the purpose of the block of code. There are two types of comments in PHP

  • Single-line Comment
  • Multi-line Comment

<?php
	// This is an example of single-line comment.
	/*
	This is an example of multi-line comment 
		   Which covers multiple lines
	*/
?>

Download the code Run the code

Case sensitivity

  • The keywords (like if, while, for, echo, etc.), function names and classes are NOT case sensitive in PHP.
  • Variable names ARE case sensitive.

Let’s look at the below example, where all the usage of echo is correct.

<?php
	echo "Welcome to the world of PHP<br>";
	ECHO "Welcome to the world of PHP<br>";
	eCHo "Welcome to the world of PHP<br>";
?>

Download the code Run the code

Now, in the below example, variable name is case-sensitive and displays the value of first echo statement only.

<?php
	$KH_Name = "John";
	echo "My name is " .  $KH_Name . "<br>";  // Output: My name is John
	echo "My name is " .  $KH_NAME . "<br>";  // Output: Notice: Undefined variable: KH_NAME
	echo "My name is " .  $kh_name . "<br>";  // Output: Notice: Undefined variable: kh_name
?>

Download the code Run the code

Statement termination by semicolons

In PHP, any statement which is an expression, is terminated by semicolon (;). In the above example, each echo statement is terminated with a semicolon.

PHP Tutorial

PHP is an acronym for Hypertext Preprocessor, a server-side programming language. PHP is used by developers to develop web pages/sites/applications with dynamic content by interacting with databases. The first version of PHP was released by Rasmus Lerdorf back in the year 1996.

  • PHP is used to develop web-based applications
  • It is very widely used
  • It is an open source scripting language and free

Most Common Functional Areas of PHP

  • Interact with database and perform create, update and delete (CRUD) operations.
  • Create, open, write, read, delete files on the server’s file system
  • Collect and retrieve form data
  • Authenticate and authorize the user-access
  • Create cookies and access them

PHP is not limited only to the above-mentioned functions. You can encrypt the data, play video, or output any text, PDF or images.

Benefits of PHP

  • PHP is totally free to use even for commercial purposes
  • PHP is being used by developers for close to two decades and it’s proven and trusted.
  • Many of world’s most popular applications such as WordPress, PHPMyAdmin  are built on PHP
  • PHP is platform independent and runs on all popular platforms like Windows, Linux, Mac, etc.
  • PHP scripts can be integrated with all major databases like MySQL, Microsoft SQL Server, Oracle, PostgreSQL, Sybase, etc.
  • It is compatible with all well-known servers like Apache, IIS, etc.
  • It supports all major protocols like IMAP, POP3, LDAP, SSL, etc.
  • It is easy to learn and program
  • PHP has a huge following and large support by community of developers

Prerequisites

Prior knowledge of HTML, JavaScript, Database and basic understanding of programming language will be very helpful.

Welcome to the world of PHP

<?php

		 echo "My first program.... Welcome to the world of PHP.";

?>

Download the code Run the code

Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .