Php Tutorial

Here we are providing a simple php tutorial.The term PHP is an acronym for PHP: Hypertext Preprocessor. PHP is a server-side scripting language designed specifically for web development. PHP can be easily embedded in HTML files and HTML codes can also be written in a PHP file. The thing that differentiates PHP with client-side language like HTML is, PHP codes are executed on server whereas HTML codes are directly rendered on the browser.

The following “Hello, World!” program is written in PHP code embedded in an HTML document:

php

The PHP interpreter only executes PHP code within its delimiters. Anything outside its delimiters is not processed by PHP, although non-PHP text is still subject to control structures described in PHP code. The most common delimiters are <?php to open and ?> to close PHP sections.

php image

Data types

PHP stores integers in a platform-dependent range, either a 64-bit or 32-bit signed integer equivalent to the C-language long type. Unsigned integers are converted to signed values in certain situations; this behavior is different from other programming languages.
Floating point numbers are also stored in a platform-specific range. They can be specified using floating point notation, or two forms of scientific notation.
PHP has a native Boolean type that is similar to the native Boolean types in Java and C++.
The null data type represents a variable that has no value; NULL is the only allowed value for this data type.
Arrays can contain elements of any type that PHP can handle, including resources, objects, and even other arrays

Php Variables

Variable is nothing it is just name of the memory location.

  • Variables in PHP starts with a dollar($) sign, followed by the name of the variable.
  • We assign a value to a variable using the equality(=) symbol.
  • A variable is created the moment you assign a value to it:
  • Variable names in PHP are case-sensitive.
Print using $echo statement

<?php

  $fruit = “Orange”;

  echo $fruit;

?>

In the above example,it print Örange

Ädding numbers

<?php

$n1 = 10;

$n2 = 20;

$sum= $n1+ $n2;  

echo “Sum = “.$sum;

?>

In the above example,the output will be 

Sum=30

Concatenation using(.)

<?php  

$v1= “Hello”;

  echo $v1.” World”;

?>

In the above example,dot(.) between variable name($v1) and string(“World”) will give the output

Hello World

$var and $$var in PHP

The $var stores any value like string, integer, float, etc.

he $$var is a reference variable that stores the value of the $variable inside it.

<?php  

$a = “hello”;  

$$a = 100;  

echo $a.“<br/>”;  

echo $$a.“<br/>”;  

echo $hello;  

?>

The output will be:

hello

100

100

 

Functions

PHP defines a large array of functions in the core language and many are also available in various extensions; these functions are well documented in the online PHP documentation.

phpfun

In the example above, getAdder() function creates a closure using passed argument $x (the keyword use imports a variable from the lexical context), which takes an additional argument $y, and returns the created closure to the caller. Such a function is a first-class object, meaning that it can be stored in a variable, passed as a parameter to other functions, etc.

Php Comments

PHP comments are used to describe any line of code so that other developer can understand the code easily.Anything within the comment is ignored or not executed.

There are two types of comments used in php  

  • Single line comments

  • Multi-lines comments

1.Single line comments

Single line comment used for short explanations Using (#) Or backslash(//)

<?php
 
# This is the first line comment

# This is the second line comment

// This is also a single line comment.

?>

2. Multi-lines comments

Multi lines comments  used to comment multiple lines.Here comments are enclosed within (/*…..*/)

<?php
 	
/* 

This is a multi line comment  

This program is used to count the numbers

This is multiline comment

*/

?>

Operators in Php

Php String operators

Php String operators include:

Operator Name Example Result
. Concatenation $string1 . $string2 Concatenation of $string1 and $string2
.= Concatenation assignment $string1 .= $string2 Appends $string2 to $string1

Php Arithmetic operators

PHP Arithmetic operators perform mathematical operation on more than one operands.It include following operators.

+Addition
Subtraction
*Multiplication
/Division and return quotient
%Divide and return modulus

Example: Divide and return Modulus

<?php

$a=20;

$b=3;

//remainder
$rem=$a%$b;

echo "remainder=".$rem."<br/>";

?>

Output:

remainder=2

This example returns the modulus of two values 20 and 3 that is 2 ($a%$b=2).

Php Assignment operators

The main assignment operator in PHP is “=”. It means that the left operand gets set to the value of the assignment expression on the right.

Assignment Meaning Description
a = b a = b The left operand gets set to the value of the expression on the right
a += b a = a + b Addition
a -= b a = a – b Subtraction
a *= b a = a * b Multiplication
a /= b a = a / b Division
a %= b a = a % b Modulus

Php Comparison operators

The PHP comparison operators are used to compare two numbers or two strings.

Operatos Description Example Meaning
== Equal to $a == $b Returns true if $a is equal to $b
=== Equal to and of the same type $a === $b Returns true if $b is equal to $b, and they are of the same type
!= Not equal to $a != $b Returns true if $a is not equal to $b
!== Returns true if $b is equal to $b, and they are of the same type $a !== $b Returns true if $b is notequal to $b, and they are of the same type
> Greater than $a > $b Returns true if $a is greater than $b
< Less than $a < $b Returns true if $a is less than $b
>= Greater than or equal to $a >= $b Returns true if $a is greater than or equal to $b
<= Less than or equal to $a <= $b Returns true if $a is less than or equal $b

Php Logical operators

The PHP logical operators are used to combine conditional statements.

Operator Name Example Result
and And $a and $b True if both $a and $b are true
or Or $a or $b True if either $a or $b is true
xor Xor $a xor $b True if either $a or $b is true, but not both
&& And $a && $b True if both $a and $b are true
|| Or $a || $b True if either $a or $b is true
! Not !$a True if $a is not true

if Statements in php

The if Statement is a conditional statement.The block of code exist inside the if statement is executed only if the specified condition is true.There are various ways to use if statement in PHP

  • if
  • if-else
  • if-else-if

If Statement

PHP if statement allows conditional execution of code. It is executed if condition is true.

<?php  

$num=5;  

if($num<10){  

echo “$num is less than 10”;  

}  

?>  

5 is less than 10

If..else Statement

PHP if ..else statement allows conditional execution of code. It is executed if condition is true else the following else block is executed.

Syntax:

if (condition){

This code is executed if condition is true;

}

else{

code to be executed if condition is false;

}

<?php  

$num=15;  

if($num<=10){  

echo “$num is less than 10”;  

}  

else{  

echo “$num is greater than 10”;  

}  

?>  

15 is greater than 10

If..else ..if Statement

Syntax:

if (condition)

{

code to be executed if condition is true;

}

else if (condition)

{    code to be executed if condition is true;

}

else

{

code to be executed if condition is false;

}

<?php

$d = date(“D”);

if ($d == “Sat”){

echo “Saturday”;

}

else if ($d == “Sun”)

{

echo “sunday!”;

}

else

{

echo “not hollydays”;

}

?>

Switch Statement in php

The expression is evaluated with the values of each case label.if there is a match, the corresponding statements after the matching label are executed.If there is no match, the default statements are executed.

<html>
   <body>
      
      <?php
         $tday = date("D");
         
         switch ($tday){
            case "Mon":
               echo "Today is Monday";
               break;
            
            case "Tue":
               echo "Today is Tuesday";
               break;
            
            case "Wed":
               echo "Today is Wednesday";
               break;
            
            case "Thu":
               echo "Today is Thursday";
               break;
            
            case "Fri":
               echo "Today is Friday";
               break;
            
            case "Sat":
               echo "Today is Saturday";
               break;
                        
            default:
               echo "Today is Sunday";
         }
      ?>
      
   </body>
</html>

for loop in php

The for loop is used when we know how many times the statement or a block of statements to be executed.

<html>
   <body>
      
      <?php
            $sum=0;     
         for( $i = 1; $i<5; $i++ ) {
            $sum=$sum+$i;
}
echo "Sum=$sum""; ?> </body> </html>

Sum=10

 

foreach in php

The foreach statement is used to loop through arrays.

Syntax:

foreach ($array as $value)

{ code to be executed;

}

For every  iteration, the value of the current array element is assigned to $value and the array pointer is moved by one.In the next iteration, we will get  next array value.

<html>
   <body>
   
      <?php
         $ar = array( 10, 20, 30);
         
         foreach( $ar as $value ) {
            echo "Number=$value <br />";
         }
      ?>
      
   </body>
</html>

Number=10

Number=20

Number=30

while loop in php

The code associated with the loop is executed if the while condition is true.

Syntax

while (condition)

	{

	 code to be executed;

	}

Example:

<?php
	
$num=1;
	
while($num<=3)
	  
{
	  
echo "The number=" . $num . "<br>";
	  
$num++;
	  
}
  
?>

output

The number=1

The number=2

The number=3

 

Do while loop in php

do..while Execute a block of code once, and then repeats the loop as long as the specified condition is true.

Syntax

do
	{
	 code to be executed;
  	}
	while (condition);

Example:

<?php
$i = 10;

do {
  echo “The number is $i <br>”;
  $i++;
while ($i <= 10);
?>

 

output

The number is 10

Strings in php

PHP strings are sequence of characters that are used to store and manipulate.There are four ways of creating strings in PHP: two of them are

  1. single quoted
  2. double quoted

1.Single quoted

It does not process special characters inside quotes. 

<?php
  
$s= ‘single-quote strings’;
 
echo $s;
  
?>

output

single-quote strings

2.Double quoted

Double-quote strings in PHP are capable of processing special characters. 

<?php
 
// double-quote strings
 
echo “double-quote strings example\n”;
 
$s= “example”;
 
echo “double-quote strings $s’\n”;

echo ‘double-quote strings $s’;
  
?>

output

double-quote strings example

double-quote strings example

double-quote strings $s

In the above program the last echo statement prints the variable name rather than printing the contents of the variables.This is because single-quotes strings in PHP do not process special characters.

String Functions in php
strlen() - Return the Length of a String

<?php
echo strlen(“Hello world!”); // outputs 12
?>

strpos() - Search a Text Within a String

If a match is found, the function returns the character position of the first match. If no match is found, it will return FALSE.

<?php
echo strpos(“Hello world!”“world”); // search the string “world” and outputs 6
?>

str_replace() - Replace Text Within a String

The PHP str_replace() function replaces some characters with some other characters in a string.

<?php
echo str_replace(“world”“Friends”“Hello world!”); // replace “world” with “Friends” and outputs Hello Friends!
?>

strrev() - Reverse a String

<?php
echo strrev(“Hello world!”); // outputs !dlrow olleH
?>

str_word_count() - Count Words in a String

<?php
echo str_word_count(“Hello world!”); // outputs 2
?>

You have successfully subscribed to the newsletter

There was an error while trying to send your request. Please try again.

ezywebbuilding will use the information you provide on this form to be in touch with you and to provide updates and marketing.