WAD 2nd Unit
WAD 2nd Unit
$variablename=value;
Rules for declaring PHP variable:
o A variable must start with a dollar ($) sign, followed by the variable name.
o It can only contain alpha-numeric character and underscore (A-z, 0-9, _).
o A variable name must start with a letter or underscore (_) character.
o A PHP variable name cannot contain spaces.
o One thing to be kept in mind that the variable name cannot start with a
number or special symbols.
o PHP variables are case-sensitive, so $name and $NAME both are treated as
different variable.
Example:
<?php
if (TRUE)
echo "This condition is TRUE.";
if (FALSE)
echo "This condition is FALSE.";
?>
Output: This condition is TRUE
PHP Integer
Integer means numeric data with a negative or positive sign. It holds only whole
numbers, i.e., numbers without fractional part or decimal points.
<?php
$dec1 = 34;
$oct1 = 0243;
$hexa1 = 0x45;
echo "Decimal number: " .$dec1. "</br>";
echo "Octal number: " .$oct1. "</br>";
echo "HexaDecimal number: " .$hexa1. "</br>";
?>
Example:
<?php
$n1 = 19.34;
$n2 = 54.472;
$sum = $n1 + $n2;
echo "Addition of floating numbers: " .$sum;
?>
PHP String
A string is a non-numeric data type. It holds letters or any alphabets, numbers,
and even special characters.
String values must be enclosed either within single quotes or in double quotes.
But both are treated differently. To clarify this, see the example below:
Example:
<?php
$company = "Javatpoint";
//both single and double quote statements will treat different
echo "Hello $company";
echo "</br>";
echo 'Hello $company';
?>
Output:
Hello Javatpoint
Hello $company
PHP Array
An array is a compound data type. It can store multiple values of same data type
in a single variable.
Example:
1. <?php
2. $bikes = array ("Royal Enfield", "Yamaha", "KTM");
3. var_dump($bikes); //the var_dump() function returns the datatype and v
alues
4. echo "</br>";
5. echo "Array Element1: $bikes[0] </br>";
6. echo "Array Element2: $bikes[1] </br>";
7. echo "Array Element3: $bikes[2] </br>";
8. ?>
Output:
array(3) { [0]=> string(13) "Royal Enfield" [1]=> string(6) "Yamaha" [2]=> string(3)
"KTM" }
Array Element1: Royal Enfield
Array Element2: Yamaha
Array Element3: KTM
You will learn more about array in later chapters of this tutorial.
PHP object
Objects are the instances of user-defined classes that can store both values and
functions. They must be explicitly declared.
Example:
<?php
class bike {
function model() {
$model_name = "Royal Enfield";
echo "Bike Model: " .$model_name;
}
}
$obj = new bike();
$obj -> model();
?>
Output:
PHP Null
Null is a special data type that has only one value: NULL. There is a convention
of writing it in capital letters as it is case sensitive.
The special type of data type NULL defined a variable with no value.
Example:
<?php
$nl = NULL;
echo $nl; //it will not give any output
?>
Output:
PHP Operators
PHP Operator is a symbol i.e used to perform operations on operands. In simple
words, operators are used to perform operations on variables or values. For
example:
o Arithmetic Operators
o Assignment Operators
o Comparison Operators
o Incrementing/Decrementing Operators
o Logical Operators
o String Operators
o Array Operators
We can also categorize operators on behalf of operands. They can be
categorized in 3 forms:
Advertisement
Arithmetic Operators
The PHP arithmetic operators are used to perform common arithmetic operations
such as addition, subtraction, etc. with numeric values.
Difference of
- Subtraction $a - $b
operands
Product of
* Multiplication $a * $b
operands
Quotient of
/ Division $a / $b
operands
Remainder of
% Modulus $a % $b
operands
$a raised to the
** Exponentiation $a ** $b
power $b
Addition same as
+= Add then Assign $a += $b
$a = $a + $b
Multiplication
Multiply then
*= $a *= $b same as $a = $a
Assign
* $b
Logical Operators
The logical operators are used to perform bit-level operations on operands.
These operators allow the evaluation and manipulation of specific bits within the
integer.
Operator Name Example Explanation
Return TRUE if
and And $a and $b both $a and $b
are true
Return TRUE if
Or Or $a or $b either $a or $b is
true
Return TRUE if
xor Xor $a xor $b either $ or $b is
true but not both
Return TRUE if
! Not ! $a
$a is not true
Return TRUE if
&& And $a && $b either $a and $b
are true
Return TRUE if
|| Or $a || $b either $a or $b is
true
String Operators
The string operators are used to perform the operation on strings. There are two
string operators in PHP, which are given below:
Operator Name Example Explanation
Concatenate both
. Concatenation $a . $b
$a and $b
First concatenate
$a and $b, then
Concatenation assign the
.= $a .= $b
and Assignment concatenated
string to $a, e.g.
$a = $a . $b
File: variable1.php
1. <?php
2. $str="hello string";
3. $x=200;
4. $y=44.6;
5. echo "string is: $str <br/>";
6. echo "integer is: $x <br/>";
7. echo "float is: $y <br/>";
8. ?>
Output:
1. <?php
2. $x=5;
3. $y=6;
4. $z=$x+$y;
5. echo $z;
6. ?>
Output:
11
strrev() :-
The strrev() function is predefined function of PHP. It is used to reverse a string.
It is one of the most basic string operations which are used by programmers and
developers.
Syntax:
string strrev ( string $string );
Example 1
1. <?php
2. $var1="Hello PHP";
3. echo "Your Number is:".$var1;
4. echo "<br>";
5. echo "By using 'strrev()' function:".strrev("$var1");
6. ?>
Output:
strlen():-
The strlen() function is predefined function of PHP. It is used to find the length of
string or returns the length of a string including all the whitespaces and special
character.
Syntax:
1. strlen(string);
Example 1
1. <?php
2. $str = 'Javatpoint';
3. echo "Your String is:".$str;
4. echo "<br>";
5. echo "By using 'strlen()' function:".strlen($str); // 10
6. ?>
Output:
str_word_count():-
Syntax:
1. str_word_count(string,return,char)
Example 1
1. <?php
2. $str="PHP Javatpoint";
3. echo "Your string is:".$str;
4. echo "<br>";
5. echo "By using str_word_count(): ".str_word_count($str);
6. ?>
Output:
The strops() is in-built function of PHP. It is used to find the position of the first
occurrence of a string inside another string or substring in a string.
Syntax:
1. int strpos ( string $haystack , mixed $needle [, int $offset = 0 ] );
Example 1
1. <?php
2. $str1="Hello Php";
3. $str2="Hello Php javatpoint!";
4. echo "First string is: ".$str1;
5. echo "<br>";
6. echo "First string is: ".$str2;
7. echo "<br>";
8. echo "By using 'strpos()' function:".strpos("$str1,$str2","php");
9. //$str1 and $str2 'Php'first letter is upper case so output is nothing.
10. // It is case-sensitive
11. ?>
Output:
Example 2
1. <?php
2. $str1="Hello php";
3. $str2=" Hello php javatpoint!";
4. echo "First string is: ".$str1;
5. echo "<br>";
6. echo "First string is: ".$str2;
7. echo "<br>";
8. echo "By using 'strpos()' function:".strpos("$str1,$str2","php");
9. //Find the position of the first occurrence of "php" inside the string
10. ?>
Output:
First string is: Hello php
First string is: Hello php javatpoint!
By using 'strpos()' function:6
str_replace() :
Syntax
The syntax of the str_replace() function is given below, which has the following
four parameters.
1. <?php
2. $string = "Hii everyone!";
3. $search = 'Hii';
4. $replace = 'Hello';
5. echo '<b>'."String before replacement:".'</br></b>';
6. echo $string.'</br>';
7. $newstr = str_replace($search, $replace, $string, $count);
8. echo '<b>'."New replaced string is:".'</br></b>';
9. echo $newstr.'</br>';
10. echo 'Number of replacement ='.$count;
11. ?>
Output:
In the above example, we can see that "Hii" is replaced with "Hello" and the
number of replacement is only 1.
The explode() function returns an array of strings created by splitting the original string.
Syntax:
1. explode (string $separator, string $originalString, int $limit)
Parameters
There are three parameters passed in the explode() function, in which two parameters
are mandatory, and the last one is optional to pass. These parameters are as follows:
$separator:
This parameter specifies the character for the point at which the original string will split.
In simple words, we can say that whenever this character is found in the string, the string
will be divided into parts.
$originalString:
$limit:
The $limit parameter specifies the number of array elements to be returned. It can
contain any integer value (zero, positive, or negative).
Return Value
This function returns an array of strings. This array of string is formed by splitting the
original string.
1. <?php
2. // original string
3. $Original_str = "Hello, we are here to help you.";
4.
5. // Passed zero
6. print_r (explode (" ",$Original_str, 0));
7. // Passed positive value
8. print_r (explode (" ",$Original_str, 4));
9. // Passed negative value
10. print_r (explode (" ",$Original_str, -3));
11. ?>
Output:
In the above example, a space character is used as separator to split the string.
Array ( [0] => Hello, we are here to help you. ) Array ( [0] => Hello, [1] => we [2] => are [3] => here
to help you. ) Array ( [0] => Hello, [1] => we [2] => are [3] => here )
Array (
[0] => Hello, we are here to help you.
) Array (
[0] => Hello,
[1] => we
[2] => are
[3] => here to help you.
) Array (
[0] => Hello,
[1] => we
[2] => are
[3] => here
)
1. <?php
2. // original string
3. $Original_str = "Hello, welcome to javatpoint.";
4. //without passing optional parameter
5. print_r (explode (" ", $Original_str));
6. ?>
Output:
In the above code, we do not pass the optional parameter, i.e., $limit. Therefore, the
explode() function splits the string into array for different indexes.
Array ( [0] => Hello, [1] => welcome [2] => to [3] => javatpoint. )
Example 3:
1. <?php
2. // original string
3. $Original_str = "Hello, welcome to javatpoint.";
4. //without passing optional parameter
5. print_r (explode ("e", $Original_str));
6. ?>
Output:
In the above code, we used the "e" character to split the string into an array. So,
wherever the "e" is found, the string will be split.
Array ( [0] => H [1] => llo, w [2] => lcom [3] => to javatpoint. )
implode() :
PHP implode() is a string function, which joins the array elements in a string. It is
a binary-safe function. In implode() function, parameters can be passed in any order.
The implode() function works same as the join() function and returns a string created
from the elements of the array. Basically, this function joins all elements of array in one
string.
Syntax
There are two syntax are available for implode() function, which are given below:
$glue (optional):
It is an optional and string type of parameter. It contains the value to join the
array elements and form a string. Basically, $glue is used to join the string.
$pieces (mandatory):
This parameter contains the array of string to implode. The array elements are
mandatory to pass in implode() function to join into one string.
Return Value
The implode() function returns the string formed from the array elements. The
string will be formed in the same order as elements passed into array. The return
type of this function is string.
Example 1:
In the below example, array elements are joined with + operator using implode()
function.
1. <?php
2. echo "Before using 'implode()' function: <br>";
3. echo "array('Welcome', 'to', 'PHP', 'tutorial') <br> <br>";
4.
5. //store array element in a variable
6. $arr = array('Welcome', 'to', 'PHP', 'tutorial');
7.
8. //join array elements in a string by + operator
9. echo "After using 'implode()' function: <br>";
10. echo implode("+",$arr);
11. ?>
Output:
o if
o if-else
o if-else-if
o nested if
PHP If Statement
PHP if statement allows conditional execution of code. It is executed if condition
is true.
If statement is used to executes the block of code exist inside the if statement
only if the specified condition is true.
Syntax
1. if(condition){
2. //code to be executed
3. }
Flowchart
Example
1. <?php
2. $num=12;
3. if($num<100){
4. echo "$num is less than 100";
5. }
6. ?>
Output:
Syntax
1. if(condition){
2. //code to be executed if true
3. }else{
4. //code to be executed if false
5. }
Flowchart
1. <?php
2. $num=12;
3. if($num%2==0){
4. echo "$num is even number";
5. }else{
6. echo "$num is odd number";
7. }
8. ?>
Output:
12 is even number
Syntax
1. if (condition1){
2. //code to be executed if condition1 is true
3. } elseif (condition2){
4. //code to be executed if condition2 is true
5. } elseif (condition3){
6. //code to be executed if condition3 is true
7. ....
8. } else{
9. //code to be executed if all given conditions are false
10. }
Flowchart
Example
1. <?php
2. $marks=69;
3. if ($marks<33){
4. echo "fail";
5. }
6. else if ($marks>=34 && $marks<50) {
7. echo "D grade";
8. }
9. else if ($marks>=50 && $marks<65) {
10. echo "C grade";
11. }
12. else if ($marks>=65 && $marks<80) {
13. echo "B grade";
14. }
15. else if ($marks>=80 && $marks<90) {
16. echo "A grade";
17. }
18. else if ($marks>=90 && $marks<100) {
19. echo "A+ grade";
20. }
21. else {
22. echo "Invalid input";
23. }
24. ?>
Output:
B Grade
Syntax
1. if (condition) {
2. //code to be executed if condition is true
3. if (condition) {
4. //code to be executed if condition is true
5. }
6. }
Flowchart
Example
1. <?php
2. $age = 23;
3. $nationality = "Indian";
4. //applying conditions on nationality and age
5. if ($nationality == "Indian")
6. {
7. if ($age >= 18) {
8. echo "Eligible to give vote";
9. }
10. else {
11. echo "Not eligible to give vote";
12. }
13. }
14. ?>
Output:
1. <?php
2. $a = 34; $b = 56; $c = 45;
3. if ($a < $b) {
4. if ($a < $c) {
5. echo "$a is smaller than $b and $c";
6. }
7. }
8. ?>
Output:
PHP Switch
PHP switch statement is used to execute one statement from multiple conditions.
It works like PHP if-else-if statement.
Syntax
1. switch(expression){
2. case value1:
3. //code to be executed
4. break;
5. case value2:
6. //code to be executed
7. break;
8. ......
9. default:
10. code to be executed if all cases are not matched;
11. }
It should be used if the number of iterations is known otherwise use while loop.
This means for loop is used when you already know how many times you want to
execute a block of code.
It allows users to put all the loop related statements in one place. See in the
syntax given below:
Syntax
1. for(initialization; condition; increment/decrement){
2. //code to be executed
3. }
Parameters
The php for loop is similar to the java/C/C++ for loop. The parameters of for loop
have the following meanings:
Advertisement
initialization - Initialize the loop counter value. The initial value of the for loop is
done only once. This parameter is optional.
condition - Evaluate each iteration value. The loop continuously executes until
the condition is false. If TRUE, the loop execution continues, otherwise the
execution of the loop ends.
Example
1. <?php
2. for($n=1;$n<=10;$n++){
3. echo "$n<br/>";
4. }
5. ?>
Output:
1
2
3
4
5
6
7
8
9
10
In case of inner or nested for loop, nested for loop is executed fully for one outer
for loop. If outer for loop is to be executed for 3 times and inner for loop for 3
times, inner for loop will be executed 9 times (3 times for 1st outer loop, 3 times
for 2nd outer loop and 3 times for 3rd outer loop).
Example
1. <?php
2. for($i=1;$i<=3;$i++){
3. for($j=1;$j<=3;$j++){
4. echo "$i $j<br/>";
5. }
6. }
7. ?>
Output:
11
12
13
21
22
23
31
32
33
Syntax
1. <?php
2. $season=array("summer","winter","spring","autumn");
3. foreach( $season as $arr ){
4. echo "Season is: $arr<br />";
5. }
6. ?>
Output:
The while loop is also called an Entry control loop because the condition is
checked before entering the loop body. This means that first the condition is
checked. If the condition is true, the block of code will be executed.
Syntax
1. while(condition){
2. //code to be executed
3. }
Alternative Syntax
1. while(condition):
2. //code to be executed
3.
4. endwhile;
PHP While Loop Flowchart
1
2
3
4
5
6
7
8
9
10
Alternative Example
1. <?php
2. $n=1;
3. while($n<=10):
4. echo "$n<br/>";
5. $n++;
6. endwhile;
7. ?>
Output:
1
2
3
4
5
6
7
8
9
The PHP do-while loop is used to execute a set of code of the program several
times. If you have to execute the loop at least once and the number of iterations
is not even fixed, it is recommended to use the do-while loop.
It executes the code at least one time always because the condition is checked
after executing the code.
The do-while loop is very much similar to the while loop except the condition
check. The main difference between both loops is that while loop checks the
condition at the beginning, whereas do-while loop checks the condition at the end
of the loop.
Syntax
1. do{
2. //code to be executed
3. }while(condition);
Flowchart
Example
1. <?php
2. $n=1;
3. do{
4. echo "$n<br/>";
5. $n++;
6. }while($n<=10);
7. ?>
Output:
1
2
3
4
5
6
7
8
9
10
Example
A semicolon is used to terminate the do-while loop. If you don't use a semicolon
after the do-while loop, it is must that the program should not contain any other
statements after the do-while loop. In this case, it will not generate any error.
1. <?php
2. $x = 5;
3. do {
4. echo "Welcome to javatpoint! </br>";
5. $x++;
6. } while ($x < 10);
7. ?>
Output:
Welcome to javatpoint!
Welcome to javatpoint!
Welcome to javatpoint!
Welcome to javatpoint!
Welcome to javatpoint!
<?php
// Simple example prompting the user for their name
$name = readline("Enter your name: ");
Output
Enter your name: Hello, ! Nice to meet you.