PHP Interview

PHP is a powerful tool that is used for creating interactive web pages. This server scripting language is a very popular choice for programmers for creating dynamic web pages.

Since PHP is a free tool, it is often seen as a perfect alternative to competitors like Microsoft ASP. In this article, we are going to discuss the most commonly asked PHP interview questions.

PHP Math:

PHP provides number of built-in function  which help in performing several operations while dealing with mathematical data. There is no installation required to use these functions. There are number of in-built functions in PHp and some of them are abs(), pi(), deg2rad(), rad2deg(),fmod(), ceil(), floor(), round().

All the in-built functions mentioned above are described below:

  1. 1.abs()
  2. pi()
  3. deg2rad()
  4. rad2deg()
  5. fmod()
  6. ceil()
  7. floor()
  8. round()

Let’s discuss them in detail. 

1.abs():

This function takes negative value as an input and return an absolute (positive value) as output. Of an integer or a float number.

Syntax:

abs(number);

In this number can be integer or float number.

Example:

<?php

Function absolute($degree)

{

Return(abs($degree));

}

$number=-8.4;

Echo (absolute($number));

?>

Output:

8.4

2.pi():

This function returns the value of pi. The constant named M_PI is identical to PI() function.

Syntax:

Pi();

Example:

<?php

Echo (pi());

?>

Output:

3.14159

3.deg2rad():

This function takes the degree value as an input and return the radian value as an output.

Syntax:

Deg2rad(number);

Example:

<?php

Function deg_radian($degree)

{

Return (deg2rad($degree));

}

$number=180;

Echo (deg_radian($number));

?>

Output:

3.14259

4.rad2deg();

This function takes an input as radian value and converts into a degree value.

Syntax:

Rad2deg(number);

Example:

<?php

Rad2deg(pi()));

?>

Output:

180

5. Fmod():

This function takes the two arguments as an input and returns the floating number remainder of division of arguments.

Syntax:

Fmod(x,y);

Here x is dividend and y is divisor. The remainder r is defined as, x=i*y+r, for some integer r.

Example:

<?php

Function result($x, $y)

{

Return fmod($x, $y);

}

$x=5.7;

$y=1.3;

Echo(result($x, $y));

?>

Output:

0.5;

6.floor();

This function takes the numeric value as an integer and return the next lowest integer value( as float) by rounding down value if necessary.

Syntax:

Floor($number);

Example:

<?php

Echo (floor(0.60).”\n”);

Echo (floor(5).”\n”);

Echo (floor(-5.9).”\n”);

?>

Output:

0

5

-6

7.Ceil();

This function takes numeric value as an input and returns the next highest integer value by rounding up the value if necessary.

Syntax:

Ceil($number );

Example:

<?php

Echo(ceil(0.60).”\n”);

Echo(ceil(-5.9)):

?>

Output:

1

-5

8.round();

This function takes the numeric value as an argument and returns the next highest integer value by rounding up the value if necessary.

Syntax:

Round(number, precision, mode);

Number specifies the value to round, precision specifies the number of decimal  digits to round( default 0) and mode specifies one of the following constants to specify the mode in which rounding occurs;

  • PHP_ROUND_HALF_UP: (set to default) it round the number up to precision decimal, when it is half way there.
  • PHP_ROUND_HALF_DOWN: Round number down to precision decimal places, when it is half way there. Rounds 1.5 to 1 and -1.5 to -1
  • PHP_ROUND_HALF_EVEN : Round number to precision decimal places towards the next even value.
  • PHP_ROUND_HALF_ODD : Round number to precision decimal places towards the next odd value.

Example:

<?php

echo(round(1.95583, 2).”\n”); 

echo(round(1241757, -3).”\n”); 

echo(round(9.5, 0, PHP_ROUND_HALF_UP).”\n”); 

echo(round(9.5, 0, PHP_ROUND_HALF_DOWN).”\n”); 

echo(round(9.5, 0, PHP_ROUND_HALF_EVEN).”\n”); 

echo round(9.5, 0, PHP_ROUND_HALF_ODD); 

?> 

PHP constants:

Variables are useful when you need to store information that can be changed as program runs. However, there may be certain situations in which you are not required to modify or change the values of variables in the program. This is accomplished using constants. Thus constant variables are those variables whose value cannot be changed during the execution of program or after once you have declared the variable. The variables with constant value will be having the same value as long as program runs.

Constants in php are defined using PHP define() function which accepts two arguments; the name of the constant and it’s value. Once defined , the value can be accessed at any time just by referring it’s name.

Example:

<?php

Define(“Site_URL”, “www.xyz.com”);

Echo “Thank you for visiting-“ .Site_URL;

?>

Output:

Thank you for Visiting- www.xyz.com

Naming Conventions for PHP Constants:

Names of constants should follow the same rules as that of variables name in PHP. Thus valid constants should start with letter or underscore, followed by any number of letter, numbers or underscores with one exception that “$ prefix is not required  for constants names”.

PHP constants can also be defined using  Const() keyword:

Const() keyword is used to define constants in PHP but only scalar constants such as integer. Float, Boolean and strings.

<?php

Const OMG=”Oh! My God”;

Echo OMG;

?>
Output:

Oh! My God

PHP OPERATORS:

Operators are used to perform operations on some values. We can also describe operators as something that take values, perform some operations on them and then gives a result.

For example, “1+ 2= 3” in this expression”+”  is an operators. It takes two values 1 and 2 , performs addition operation on them to give 3.

The addition (+) is the operator that tells PHP to add  two variables or values, whereas greater than (>) symbol is the operator that tells the PHP to compare two values.

Just like other programming languages Php also supports various types of operations like the Arithmetic operation( addition, subtraction, multiplication, divison, etc.), logical operations( AND, OR. Etc.). Increment and Decrement operations etc.

Operators are used to perform operations on PHP variables and simple values.

In PHP there are total 7 types of operators, they are:

  1. Arithmetic Operators
  2. Assignment Operators
  3. Comparison Operators
  4. Increment/Decrement Operators
  5. Logical Operators
  6. String Operators
  7. Array Operators

There are a few additional operators as well like, Type operator, Bitwise operator, Execution operators etc.

Based on how these operators are used, they are categorised into 3 categories:

  1. Unary Operators: Works on a single operand(variable or value).
  2. Binary Operators: Works on two operands(variables or values).
  3. Ternary Operators: Works on three operands.

PHP Arithmetic Operators

The arithmetic operators are used to perform common arithmetic operations such as addition, subtraction, multiplication, division, etc.

Below is the complete list of PHP arithmetic operators:

OperatorDescriptionExampleResult
+Addition$x+$YSum of $x and $Y
Subtraction$x-$ySubtraction of $x and $Y
*Multiplication$x*$yMultiplication of $x and $Y
/Division$x/$yDivision of $x and $Y
%Modulus$x%$yModulus of $x and $Y

The example of all the arithmetic operators in PHP program is as follows:

<?php

$x =10;

$y=4;

Echo($x +$y); //outputs:14

 Echo($x -$y); //outputs:6

Echo($x *$y); //outputs:40

Echo($x /$y); //outputs:2.5

Echo($x %$y); //outputs:2

?>

PHP Assignment Operators:

The PHP assignment operators are used to assign values to variables.

OperatorDescriptionExampleIs same as
=Assign$x=$y$x=$y
+=Add and assign$x+=$y$x= $x + $y
-=Subtract and assign$x-=$y$x= $x – $y
*=Multiply and assign$x*=$y$x= $x * $y
/=Divide and assign quotient$x/=$y$x= $x /$y
%=Divide and assign modulus$x%=$y$x= $x % $y

The example of all the assignment operators in PHP program is as follows:

<?php

$x=10;

echo $x; // output:10

$x=20;

$x +=30;

echo $x; // output: 50

$x= 50;

$x-=20;

Echo $x: //output:30

$x= 5;

$x*=25;

Echo $x: //output:125

$x= 50;

$x/=10;

Echo $x: //output:5

$x= 100;

$x%=15;

Echo $x: //output:10

?>

PHP comparison operators

The Comparison operators in PHP are used to compare two values in Boolean Fashion.

OperatorsNameExampleResult
==Equal$x = = $yTrue if $x is equal to $y
===Identical$x= = = $yTrue if $x is equal to $y, and they are of same type
!=Not equal4x!= $yTrue if $x is not equal to $y
< >Not eual$x < >$yTrue if $x is not equal to $y
!= =Not identical$x! = = $yTrue if $x is not  equal to $y, or they are not of same type
<Less than$x < $yTrue if $x is less than $y
>Greater than$x > $yTrue if $x is greater than $y
>=Greater than or equal to$x>=$yTrue if $x is greayer than or equal to $y
<=Less than or equals to$x< =$yTrue if $x is lessthan or equal to $y

The example of all the comparison operators in PHP program is as follows:

<?php

$x=25;

$y=35;

$z=”25”;

Var_dump( $x = =$z); // output: boolean true

Var_dump( $x = =  =$z); // output: boolean false

Var_dump( $x ! =$y); // output: boolean true

Var_dump( $x <$y); // output: boolean true

Var_dump( $x >$y); // output: boolean false

Var_dump( $x < =$y); // output: boolean true

Var_dump( $x > =$y); // output: boolean false

?>

PHP incrementing and decrementing operators:

The increment and decrement operator in PHP are used to increment or decrement a variable’s value.

OperatorsNameEffect
++$xPre-incrementIncrements $x by one, then returns $x
$x++Post-incrementReturns $x, then increment $x by one
–$xPre-decrementDecrements $x by one, then returns $x
$x–Post-decrementReturns $x, then decrement $x by one

The example of all the increment and decrement operators in PHP program is as follows:

<?php

$x =10;

echo ++$x; // outputs:11

echo $x; // outputs: 11

$x =10;

echo $x++; // outputs:10

echo $x; // outputs: 11

$x =10;

echo –$x; // outputs:9

echo $x; // outputs: 9

$x =10;

echo $x–; // outputs:10

echo $x; // outputs: 9

?>

Php Logical Operators

The logical operators are typically used to combine conditional sattements.

OperatorsnameExampleResult
andAnd$x and $yTrue if both $x and $y are true 
orOr$x or $yTrue if either  $x or $y is  true
xorXor$x xor $yTrue if either  $x and $y is true, but not both
&&And$x && $yTrue if both $x and $y are true
||Or$x || $yTrue if either $x or  $y is true
!Not! $xTrue if both $x is not true

The example of all the logical  operators in PHP program is as follows:

<?php

$year =2014

// Leap years are divisible by 400 or by 4 but not by 100

If(($ year % 400= =0) || (($year %100 != 0) && ($ year 5 4 = =0)))

{

Echo “ $year  is a leap year.”;

}

Else

{

Echo”$year is not a leap year.”;

}

?>

PHP string Operators:

There are two operators that are specifically designed for string characters.

OperatorsDescriptionExampleResult
.Concatenation$str1. $str2Concatenation of $str1 and $str2
.=Concatenation assignment$str1.= $str2Appends the $str2 to $str1

The example of all the string operators in PHP program is as follows:

<?php

$x =”Hello”;

$y=”World!”;

Echo $x. $y;// outputs: Hello World!

$x.=$y;

Echo $x; // outputs: Hello world!

?>

PHP Array Operators:

The array operators are used to compare arrays.

OperatorsNameExampleResult
+Union$x + $yUnion of $x and $y
= =Equality$x = = $yTrue if $x and $y have the same key/ value pair
= = =Identity$x = = =$yTrue if $x and $y have the same key/ value pair in the same order and of the same types
!=Inequality$x!=$yTrue if $x is not equal to $y
< >Inequality$x< >$yTrue if $x is not equal to $y
!= = =Non-identity$x!= =$yTrue if $x is not identical to $y

The example of all the array operators in PHP program is as follows:

<?php

$x= array(“a”=>”red”, “b”=>”Green”,”c”=>”Blue”);

$y= aaray(“u”=>”Yellow”,”v”=>”Orange”,”w”=>”Pink”);

$z=$x+$y;// union of $x and $y

Var_dump($z);

Var_dump($x= = $y); // outputs: Boolean false

Var_dump($x= = = $y); // outputs: Boolean false

Var_dump($x! = $y); // outputs: Boolean true

Var_dump($x< >$y); // outputs: Boolean true

Var_dump($x!= = $y); // outputs: Boolean true

?>

PHP spaceship operators

PHP 7 introduces a new spaceship operator(< =>) which can be used for comparing two expressions. It is also known as combined comparison operator.

The spaceship operator returns 0 if both operands are equal, 1 if the left operand is greater and -1 if the right operand is greater.

It basically provides three-way comparison as shown in the following table;

Operators< => equivalent
$x < $y($x < = >$y) = = = -1
$x <=$y($x < = >$y) = = = -1 || ($x < = >$y) = = = 0
$x ==$y($x < = >$y) = = = 0
$x!=$y($x < = >$y)! = = 0
$x>=$y($x < = >$y) = = = 1||($x < = >$y) = = = 0
$x>$y($x < = >$y) = = = 1

The example of all the spaceship operators in PHP program is as follows:

<?php

// comparing integers

Echo 1< = >1; // outputs: 0

Echo 1< = >2; // outputs:-1

Echo 2< = >1; // outputs: 1

//comparing floats

Echo 1.5< = >1.5; // outputs: 0

Echo 1.5< = >2.5; // outputs: -1

Echo 2.5< = >1.5; // outputs: 1

//comparing strings

Echo “x”< = >”x”; // outputs: 0

Echo “x”< = >”y”; // outputs: -1

Echo “y”< = >”x”; // outputs: 1

?>

The Ternary operator

The Ternary operator provides a shorthand way of writing the If…..else statements. It is represented by question (?) mark symbol and it takes three operands; a condition to check, a result for true, and a result for false.

Let us understand the ternary operator by considering the following example:

<?php

If($age < 18)

{

Echo”child”:// Display child if age is less than 18

}

Else

{

Echo “Adult”:// Display Adult if age is greater than 18

}

?>

Using the ternary operator the same code could be written in more compact way as follows:

<?php

Echo ($age <18)  ? ‘Child’: “Adult’;

?>

The ternary operator in the example above selects the value on the left of colon if the condition evaluates to true and the value on right of colon if the condition evaluates to false.

The Null Coalescing operator:

PHP 7 introduces a new Null Coalescing Operator (??) which you can use as a shorthand where you need to use ternary operator in conjunction with  isset() function.

To understand this in better way let us consider the following lines of code. 

It fetches the value of $_Get[‘name’]. if it does not exist or Null, it returns ‘ anonymous’.

<?php

$name= isset($_Get[‘name’])? $-Get[‘name’]: ‘anonymous’;

?>

Using the Null Coalescing operator the above code could be written as:

<?php

$name=$_Get [‘name;] ?? ‘anonymous’;

?>

PHP LOOPS:

Loops are used to execute the same block of code again and again. As long as certain condition is met. The basic idea behind the loop is to automate the repetitive tasks within the program to save the time and effort. 

PHP supports four different types of loops:

While loop :

It loops through a block of code as long as the condition that is specified evaluates to true.

Do…while loop:

In this  loop block of code is executed once and then condition is evaluated. If the condition evaluates to true then the statement is repeated as long as specified condition evaluated to true.

For loop:

It loops through a block of code until the counter reaches a specified number.

Foreach loop:

It loops through a block of code for each element in an array. This loops works specifically with arrays.

PHP while loop:

The While statement will loop through a block of code as long as the condition specified in while statement evaluates to true.

Syntax for while loop is as:

While(Condition to be evaluated)

{

//code to be executed

}

The example below defines a loop which starts with $i=1. The loop will continue to run as long as $i is less than or equal to 3. The $i will increase by 1 each time the loop runs:

<?php

$i=1;

While($i<=3)

{

$I++;

Echo” The number is “. $i . “<br>”;

}

?>

PHP do…….while loop:

The do-while loop is a variant of while loop, which evaluates the condition at the end of each loop iteration. With the do-while loop the block of code  is executed only once, and then the condition specifies is evaluated, if the condition is true then the statement is repeated as many times as the specified condition evaluates to true.

The do-while statement is an exit-controlled statement as test condition is checked at the end of do-while loop and therefore body is executed unconditionally for the first time.

The Syntax for do-while loop is:

Do

{

//code to be executed

}

While(condition to be evaluated);

<?php

$i=1;

Do

{

$i++;

Echo” The number is” .$i. “<br>”;

}

While($i<=3);

?>

PHP For Loop:

The for loop is another form of looping statement which is the most versatile, convenient and popular of three loop structures. It is used in those cases where a programmer known in advance that for how many number of times a statement or block of code will be executed.

The Syntax for For lop is as follows:

<?php

For (initialize; condition; increment)

{

//code to be executed

}

?>

In the above code “initialize” usually an integer ; it is used to set the counter’s initial value.

“Condition” the condition that is evaluated for each php execution. If it evaluates to true then execution of for…loop is terminated and if it evaluates to false, the execution of for…loop continues.

“Increment” is used to increment the initial value of counter integer.

Example:

<?php

For($i=0; $i<10; $i++)

{

$product =10 * $i;

Echo “ The product of 10 *$i is $product  <br/>”;

}

?>

Output:

The product of 10 * 0 is 0

The product of 10 * 1 is 10

The product of 10 * 2 is 20

The product of 10 * 3 is 30

The product of 10 * 4 is 40

The product of 10 * 5 is 50

The product of 10 * 6 is 60

The product of 10 * 7 is 70

The product of 10 * 8 is 80

The product of 10 * 9 is 90

PHP For Each Loop:

The php for each loop is used to iterate through array values.

It has the following syntax:

<?php

Foreach($array_variable as $array_variable)

{

//block of code to be executed

}

?>

“$array_data” is the array variable to be looped through

:$array_value” is the temporary variable that holds the current array item values.

“block of code..” is the piece of code that operates on array values.

Example:

<?php

$animal_list= array(“Lion”,”Wolf”,”Dog”,”Leopard”,”Tiger”);

Foreach($animal_list as $array_values)

{

Echo $array_values, “<br>”;

}

?>

Output:

Lion

Wolf

Dog

Leopard

Tiger

Summary:

The while..loop is used to execute a block of code as long as set condition is made to be false

The do..while loop is used to execute the block of code at least once then the rest of execution is dependent  on the evaluation of set condition.

The for loop is used   to execute a block of code for specified number of times

The foreach loop is used to loop through arrays.

Php Conditional statements:

These are also refered as Decision control Statements. These statements alter the normal sequential execution of statements of program depending upon the test condition to be carried out at a particular point in the program.The decision to betaken regarding where the control shoukd transfer depends upon the outcome of test condition.

You can create test condition in the form of expression that evaluates to either true or false then you can perform certain actions based on the result.

There are several statements in PHP that you can use to make decisions.

The if statement

The if..else statement

The if…elseif..else statement

The switch ..case statement

The if statement:

It is used to execute a statement or a statement block if the condition is true.

The syntax for if statement is:

If(Condition)

{

Statement(s);

}

The keyword IF tells the interpreter that a decision control statement is to executed. The condition following the if keyword includes any relational or logical expression which is always enclosed within the parenthesis. If the condition is TRUE then the statements in the block are executed. If the condition is false then block of statements is ignored and the control transfers to next statement following the If construct.

The following example will give the output “ Have a nice weekend” if the current day is Friday:

<?php

$d = date(“D”);

If($d = = “Fri”)

{

Echo “have a nice weekend”;

}

?>

The if…else statement:

In case of if statement , the block of statements are executed inly if the condition is true. But if the condition is false nothing is don and the control is transferred to next statement following If construct. However, if specific statements are to be executed in both the cases either condition is true or fasle  then if-else statement is used. 

The if-else statement allows the programmer to execute a block of statement following the if keyword when condition is true and execute a different statement block following else keyword when condition evaluates to false.

The general form of if-else statement is:

If(condition)

{

Statements to be executed

}

Else

{

Statements to be executed

}

The following example will give output “ Have a nice weekend “ if the current day is Friday, otherwise it will give output as “ have a nice day”:

<?php

$d = date(“D”);

If($d= =  “Fri”)

{

Echo” have a nice weekend”;

}

Else

{

Echo “have a nice day”;

}

?>

The if…elseif…else statement  

The if…elseif…else statement is the special statement that is used to combine multiple if..else statement.

The general form is as follows:

If(condition 1)

{

//code to be executed if condition 1  is true

}

Elseif (condition 2)

{

//code to be executed if condition 1 is false and condition 2 is true}

Else

{

//code to be executed if both condition 1 and condition 2 are false

}

The following example will give output “Have a nice weekend” if current day is Friday, and “ Have a nice Sunday”, if the current day is Sunday, otherwise it will give output “ Have a nice day”

<?php

$d = date(“D”);

If($d= = “fri”)

{

Echo “Have  a nice weekend”;

}

Elseif ($d ==”sun”)

{

Echo “ Have a nice Sunday”;

}

Else

{

Echo “ Have a nice day”;

}

?>

PHP Switch Statement:

PHP switch statement is used to execute one statement from multiple conditions. It works like PHP if-else-if statement. It is a multi-way decision making statement which selects one of several alternatives based on value of an integer variable or expression. The switch statement is convenient to be used if there are large number of alternative paths. It is more efficient than if-else-if  statement as several conditions need to be evaluated before a particular condition is satisfied.

Syntax:

Switch(expression)

{

Case value 1:

//code to be executed

Break;

Case value 2;

//code to be executed;

Break;

…..

Default:

Code to be executed if all cases are not matched

}

The default statement is an optional statement . Even it is not important statement. The default statement should be the last statement.There can be only one default statement , more than one default statement can lead to a fatal error.

Each case have  a break statement that terminates the sequential execution of statements. Break statement is optional to use , if it is not used then all the statements will execute after finding the matched case value.

Php allows you to use string, number, character as well as functions in the switch case statement.

We can also use semi colon(;) instead of colon(:) it will not generate any error.

Example:

<?php

$num=20;

Switch($num)

{

Case 10;

Echo(“number is equal to 10”);

Break;

Case 20;

Echo(“number is equal to 20”);

Break’

Default:

Echo(”number is not equal to 10,20 and 30);

}

?>

Output:

Number is equal to 20

PHP switch statement with characters:

We will pass a character in switch expression to check whether  it is vowel or consonant. If the passed character is A, E, I, O, U, it will be vowel otherwise consonant.

  <?php

$ch=’U’;

Switch(ch)

{

Case ‘a’;

Echo “Given character is vowel”;

Break;

Case ‘e’;

Echo “Given character is vowel”;

Break;

Case ‘i’;

Echo “Given character is vowel”;

Break;

Case ‘o’;

Echo “Given character is vowel”;

Break;

Case ‘u’;

Echo “Given character is vowel”;

Break;

Case ‘A’;

Echo “Given character is vowel”;

Break;

Case ‘E’;

Echo “Given character is vowel”;

Break;

Case ‘I’;

Echo “Given character is vowel”;

Break;

Case ‘O’;

Echo “Given character is vowel”;

Break;

Case ‘U’;

Echo “Given character is vowel”;

Break;

Default:

Echo” Given character is consonant”;

Break;

}

?>

Output:

Given character is vowel

Php switch statement with String:

<?php

$ch=”B.tech”;

Switch($ch)

{

Case “BCA”;

Echo  “BCA is 3 year course”;

Break;

Case “Bsc”;

Echo “Bsc is 3 year course”;

Break;

Case “B.Tech”;

Echo “B.Tech is 4 year course”;

Break;

Case”B,Arch”;

Echo “B.Arch is 5 year course”;

Break;

Default:

Echo “wrong choice”;

Break;

}

?>

Output:

B.Tech is 4 years course

PHP Switch statement is fall-through:

PHP switch statement is fall through. It means it will execute all the statements after getting the first matched. If break statement is not found.

<?php

$ch=’c’;

Switch($ch)

{

Case ‘a’;

Echo “choice a”;

Break;

Case ‘b’;

Echo “choice b”;

Break;

Case ‘c’;

Echo “choice c”;

Break;

Case ‘d’;

Echo “choice d”;

Break;

Default:

Echo “casr a,b,c and d is not found”;

}

?>

Output:

Choice c

Choice d

Case a,b,c and d is not found

PHP nested switch statement

Nested switch statement means switch statement into another switch statement.

<?php

$car=”Hyundai”;

$model=”Tuncion”;

Switch($car)

{

Case “Honda”;

Switch($model)

{

Case “Amaze”;

Echo”Honda Amaze Price is 5.93-9.79 lakh”;

Break;

Case “City”;

Echo”Honda City Price is 9.93-14.31 lakh”;

Break;

}

Break;

Case “Renault”;

Switch($model)

{

Case “Duster”;

Echo “Renault duster price is 9.15-14.83 lakh”;

Break;

Case “Kwid”;

Echo”Renault kwid Price is 3.15-5.44 lakh”;

Break;

}

Break;

Case “hyundai”;

Switch($model)

{

Case “Creta”;

Echo”Honda Creta Price is 11.42-18.73 lakh”;

Break;

Case “Tucson”;

Echo”Honda Tucson Price is 22.39-32.07lakh”;

Break;

Case “Xcent”;

Echo”Honda Xcent Price is 6.5-10.05 lakh”;

Break;

}

Break}

?>

Output:

Hyundai Tucson price is 22.39-32.07 lakh

PHP Functions:

PHP function is a piece of code that can be reused many times. It can take input as argument list and return value. There are thousands of in-built PHP functions.

Advantages of PHP functions:

Code reusability:

Less code

Easy to access

Reduce duplication of code

Information Hiding

There are two types of functions involved in PHP.

Built-in functions: These functions are part of php language and therefore these functions are pre-determined functions.

The built-in functions in php are phpinfo(), rbs() or abs().

User-defined functions:

The user-defined functions are created by programmer to cover their needs in the programme.

PHP user-defined functions:

We can declare and call user-defined function easily.

Syntax:

Function functionname()

{

//code to be executed

}

Example:

<?php

Function sayHello()

{

Echo “Hello PHP Function”;

}

sayHello(); //Calling function

?>

Output:

Hello PHP Function

PHP function arguments:

We can pass the information in PHP function through arguments which are separated by commas.

Php support’s

Call by Value()

Call by Reference()

Default argument list()

Variable-length agreement list()

Example of passing single argument in PHP:

<?php

Function sayHello($name)

{

Echo “Hello $name <br/>”;

}

sayHello(“vina”);

sayHello(“shina”);

sayHello(“reema”);

?>

Output:

Hello vina

Hello Shina

Hello reema

Example to pass two arguments in PHP function:

<?php

Function sayHello($name, $age)

{

Echo “Hello $name, you are $age year old <br/>”;

}

sayHello(“vina, 27);

sayHello(“Reema, 28);

sayHello(“Shina, 29);

?>

Output:

Hello vina, you are 27 year old

Hello Reema, you are 28 year old

Hello Shina, you are 29 year old

PHP Call by Reference method:

Value passed to the function does not modify the actual value by default. We can modify by passing value by reference.

By default, value passed to the function is call by value. You can pass value by reference and to do so you need to specify ampersand(&) symbol before the argument name.

Example to show call by reference method in PHP:

<?php

Function adder(&$str2)

{

$str2=’Call by reference’;

}

Str=’Hello’;

adder($str);

echo “$str”;

?>

Output:

Hello call by reference

PHP function: default argument value

We can specify a default argument value in function. If you do not specify any argument, it will take the default argument.

Example:

<?php

Function sayHello($name=”Vina”)

Echo “Hello $name <br/>”;

}

sayHello(“Rajesh”);

sayHello(); //passing no value

sayHello(”John”);

?>

Output:

Hello rajesh

Hello Vina

Hello John

PHP Function: Returning Value

<?php

Function cube($n)

{

Return $n*$n*$n;

}

Echo “cube of 3 is”. Cube(3);

?>

Output:

Cube of 3 is 27

ARRAYS:

An array is a collection of logically related variables of identical data type that share a common name. It is used to handle large amount of data. Without the need to declare many individual variables separately. The array elements are stored in contiguous memory locations. Al the array elements can be either of primitive type like int, char, float, double, et cot they can be of reference type like class. Each array element is accessed and manipulated using array name followed by index or subscript that specify the position of array element within the array. The single subscript is required to access the element of single-dimensional array and two subscripts are required to access the elements of two-dimensional array. All the arrays whose elements are accessed using two or more subscripts are referred as multi-dimensional arrays. Each subscript is enclosed in square bracket and it should be expressed as non-negative integer constant or expression. The primary advantage of an array is that this stores the data in such a way that it can be easily manipulated.

Declaring an array:

Before you could use array, you must declare a variable to reference an array and specify the type of an array the variable can reference. 

Syntax for declaring an one dimensional array is:

<?php

$variable_name[];

?>

Accessing an array element:

Once the array is declared, you can access the array element by using the name of the array followed by an index enclosed between a pair of square brackets. The index or subscript indicates the position of element in an array. The index of first element in array is always zero(0), the second element has an index 1 and so on. The index of last element is always the 1 less than number of elements in an array.

Syntax for accessing the elements of an array:

$arrayRefVar[index];

To assign a value to an element of one dimensional array use the following syntax:

$arrayRefVar[index]=value;

$num[2]=15;

Initializing an array:

When an array is created, each element of the array is set to default value according to it’s type. However it is also possible to provide an another value to elements in an array other than their default value. This is made possible using array initialization. Arrays can be initialized by providing values using a comma separated list within curly braces following their declaration.

The syntax of array initialization is

$arrayname=array{value1, value 2,…};

Example:

$num=array{5,15,25,30,50};

In the above example an array named num is created with index value 0,1,2,3,4. The element num[0] is initialized to 5, num[1] is initialized to 15 and so on.

The above initialization statement is equivalent to 

PHP has three types of arrays:

Indexed arrays

Associative arrays

Multidimensional arrays

PHP Indexed Arrays:

PHP index is represented by number which starts from 0.we can store number, string, objects in php array and all elements of array are assigned to an index number by default.

There are two ways to define indexed arrays as follows:

$season=array[“summer”,”winter”,”spting”,”autumn”];

Second way to define an index array is:

$season[0]=”summer”;

$season[1]=”winter”;

$season[2]=”spring”;

$season[3]=”autumn”;

Example with php program:

<?php

$season=array[“summer”,”winter”,”spring”,”autumn”];

{

Echo “seasons are: $season[0], $season[1], $season[2], $season[3]”;

}

?>

Output:

Seasons are summer, winter, spring, autumn

PHP Associative array:

We can associate name with each array element in php using => symbol.

The first method that can be used to declare associative array is as:

$salary= array[“Sonu”=>”35000”,”Monu”=>”45000”,”Raman”=>”60000”];

The second method that could be used to declare associative array in php is as follows:

$salary[“Sonu”]=”35000”;

$salary[“Monu”]=”45000”;

$salary[“Raman”]=”60000”;

Example in php program is as follows:

<?php

$salary= array[“Sonu”=>”35000”,”Monu”=>”45000”,”Raman”=>”60000”];

{

Echo “Sonu salary:” .$salary[“Sonu”].”<br>”;

Echo “Monu salary:” .$salary[“monu”].”<br>”;

Echo “Raman salary:” .$salary[“raman”].”<br>”;

}

?>

Output:

Sonu salary: 35000

Monu salary: 45000

Raman salary: 60000

Multidimensional array in PHP;

The multidimensional array is also referred as array of arrays. Thus it is used to represent tabular data in array form. Multidimensional array can be represented in matrix in the form of row* column.

Example:

$emp= array

(

Array=(1, “Sonu”,40000),

Array=(2,”Monu”,45000),

Array(3,”Raman”,60000)

);

Let us understand the php multidimensional array with the help of following tabular information:

IDNameSalary
1Sonu40000
2Rahul50000
3John30000

<?php

$emp=array

(

Array=(1,”Sonu”,40000).

Array=(2,”Rahul”,50000),

Array=(3,”John”,30000)

);

For($row=0;$row<3;$row++)

{

For($col=0;$col<3;$col++)

{

Echo $emp[$row][$col].””;

}

Echo “<br/>”;

}

?>

Output:

1 Sonu  40000

2 Rahul 50000

3 John  30000

PHP array functions:

Count Function:

Count function in php is used to count the number of elements an array contains.

<?php

$lecturers=array(“M.smith”,”M.john”,”M.Binda”);

Echo count($lecturers);

?>

Output:

3

Is-array function:

This function is used to determine whether a variable is an array or not.

<?php

$lecturers(“M.smith”,”M.john”,”M.binda”);

Echo is_array($lecturers);

?>

Output:

1

Sort function:

Sort function is used to sort arrays by values. If the values are alphanumeric it sorts the array into alphabetical order. If the values are numeric values, it sorts them into ascending order.

<?php

$persons=array(“Marry”=>”Female”,”John”=>”Male”, “Mariam”=>”Female”);

Sort($persons);

$print_r($persons);

?>

Output:

Array([0]=>female [1]=>Female [2]=>Male)

Ksort function:

The ksort function is used to sort the array using the key.

<?php

$persons=array(“Marry”=>”Female”,”John”=>”Male”, “Mariam”=>”Female”);

ksort($persons);

$print_r($persons);

?>

Output:

Array( [john]=>Male, [Mary]=>Female,[“Mariam”]=>Female)

Assort function:

The assort function in php is used to sort the array using the values.

<?php

$persons=array(“Marry”=>”Female”,”John”=>”Male”, “Mariam”=>”Female”);

asort($persons);

$print_r($persons);

?>

Output:

Array([Mary]=>Female, [Mariam]=>Female,[John]=>Male)

The explode function:

This function is used to split the string into multiple parts and then return as an array.

<?php

$string=”one,two,three”;

$array=explode(“ “,$string);

Echo ‘<pre>’;

Print_r($array);

?>

Output:

Array

[0]=>one

[1]=>two

[2]=>three

)

The implode function:

This function is the opposite to explode function. This function generates a string by joining all elements of an array with a glue string between them.

<?php

$string=”one,two,three”;

$string=implode(“ “,$string);

Echo $string;

?>

Output:

One, two, three

The array_push function:

The array_push function is used to add new elements at the end of an array.

<?php

$array=[‘one’,’two’,’three’];

Array_push($array,’four’);

Echo ‘<pre>’;

Print_r($array);

?>

Output:

Array(

[0]=>one

[1]=>two

[2]=>three

[3]=>four

The array_pop function:

The array_pop function does opposite to array_push function. This function helps in removing the element from the end of an array.

<?php

$array=[‘one’,’two’,’three’];

$element=Array_push($array);

Echo ‘<pre>’;

Print_r($array);

?>

Output:

Array(

[0]=>one

[1]=>two

)

PHP FAQs

1. Why to Learn PHP?

You should learn PHP because it is one of the most widely used technologies in the world. From small scale businesses to top multinational organizations, 80% of the top websites use PHP. Whether you want to work as a freelancer or a full-time employee, when it comes to website building, it is likely that your client will look for PHP knowledge. Leading companies like Facebook have heavily invested in PHP to make its platform more responsive and user friendly.  

2. Characteristics of PHP

PHP is quite flexible when it comes to server side programming, making it indispensable for website development. The characteristics of PHP include

  • Beginner Friendly: Beginners often prefer PHP because of its simplicity. PHP codes are easy to learn, making it a favourite among many non-programmers. It is well supported and accessed by a large community of users, making learning materials easily available. 
  • Flexible: PHP allows you more flexibility since it’s a dynamic language. You can build features according to your own preferences as there are no hard rules that you need to follow. PHP is easier to edit as identifying and correcting errors is not difficult.
  • Open source: One of the biggest advantages of PHP is that it is open source. Users can just download it and start using it for free. Additionally, it supports a range of popular databases like SQLite, MySQL, Oracle and more.

3. Applications of PHP

Applications of PHP include:

  • Building Web Pages and web applications
  • Building desktop graphics user interface based applications
  • Support for Web Content Management Systems:
  • Image Processing and Graphic Design:
  • Data Representation

4. Why use PHP?

Apart from supporting all the major databases like MySQL, SQLite, and more, PHP is also excellent when it comes to online documentation. The functions are widely used so that there are plenty of references available online. If you ever need help handling PHP, you will easily find it online. 

So, these were some of the most common PHP questions. Keep an eye on this space. We will keep adding to this list.

Because of its free availability, PHP is one of the most used languages in web development.

1

LEAVE A REPLY

Please enter your comment!
Please enter your name here

1 × three =