0% found this document useful (0 votes)
2 views

PHP

The document provides an overview of PHP scripting, including syntax, case sensitivity, comments, variables, conditional statements, loops, and arrays. It explains how to create and manipulate indexed, associative, and multidimensional arrays, as well as common functions for sorting and modifying arrays. Additionally, it covers string manipulation techniques such as searching, replacing, and converting strings to arrays.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

PHP

The document provides an overview of PHP scripting, including syntax, case sensitivity, comments, variables, conditional statements, loops, and arrays. It explains how to create and manipulate indexed, associative, and multidimensional arrays, as well as common functions for sorting and modifying arrays. Additionally, it covers string manipulation techniques such as searching, replacing, and converting strings to arrays.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 19

PHP

A PHP script can be placed anywhere in the document.

A PHP script starts with <?php and ends with ?>:

<?php

// PHP code goes here

?>

The default file extension for PHP files is ".php".

A PHP file normally contains HTML tags, and some PHP scripting code.

ExampleGet your own PHP Server

A simple .php file with both HTML code and PHP code:

<!DOCTYPE html>

<html>

<body>

<h1>My first PHP page</h1>

<?php

echo "Hello World!";

?>

</body>

</html>

PHP Case Sensitivity

In PHP, keywords (e.g. if, else, while, echo, etc.), classes, functions, and user-defined functions are
not case-sensitive.

<html>

<body>

<?php

ECHO "Hello World!<br>";

echo "Hello World!<br>";

EcHo "Hello World!<br>";

?>
</body>

</html>

However; all variable names are case-sensitive!

<html>

<body>

<?php
$color = "red";

echo "My car is " . $color . "<br>";

echo "My house is " . $COLOR . "<br>";

echo "My boat is " . $coLOR . "<br>";

?>

</body>

</html>

Comments

// This is a single-line comment

# This is also a single-line comment

/* This is a

multi-line comment */

Variables

$x = 5;

$y = "John";
PHP if Statements

In PHP we have the following conditional statements:

 if statement - executes some code if one condition is true

 if...else statement - executes some code if a condition is true and another code if that
condition is false

 if...elseif...else statement - executes different codes for more than two conditions

 switch statement - selects one of many blocks of code to be executed

<html>
<body>
<?php
if (5 > 3) {
echo "Have a good day!";
}
?>
</body>
</html>

Ex.2

<html>

<body>

<?php

$t = 14;

if ($t < 20) {

echo "Have a good day!";

?>

</body>

</html>

Ex.3

<html>

<body>
<?php

$t = date("H");

if ($t < "20") {

echo "Have a good day!";

} else {

echo "Have a good night!";

?>

</body>

</html>

Short Hand If
<html>
<body>
<?php
$a = 5;
if ($a < 10) $b = "Hello";
echo $b
?>
</body>
</html>

Nested if

<html>
<body>
<?php
$a = 13;
if ($a > 10) {
echo "Above 10";
if ($a > 20) {
echo " and also above 20";
} else {
echo " but not above 20";
}
}
?>
</body>
</html>

PHP switch Statement

The switch statement is used to perform different actions based on different conditions.
<html>

<body>

<?php
$favcolor = "red";
switch ($favcolor) {
case "red":
echo "Your favorite color is red!";
break;
case "blue":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, blue, nor green!";
}
?>
</body>

</html>

PHP Loops

In PHP, we have the following loop types:

 while - loops through a block of code as long as the specified condition is true

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

 for - loops through a block of code a specified number of times

 foreach - loops through a block of code for each element in an array

While loop

<html>

<body>

<?php
$i = 1;
while ($i < 6) {
echo $i;
$i++;
}
?>
</body>

</html>
The PHP do...while Loop

The do...while loop will always execute the block of code at least once, it will then check the
condition, and repeat the loop while the specified condition is true.

<html>

<body>

<?php
$i = 1;
do {
echo $i;
$i++;
} while ($i < 6);
?>
</body>

</html>

The PHP for Loop

The for loop is used when you know how many times the script should run.

Syntax

for (expression1, expression2, expression3) {

// code block

 expression1 is evaluated once

 expression2 is evaluated before each iteration

 expression3 is evaluated after each iteration

<html>

<body>

<?php

for ($x = 0; $x <= 10; $x++) {

echo "The number is: $x <br>";

?>

</body>

</html>
Break statement

<html>

<body>

<?php

for ($x = 0; $x <= 10; $x++) {

if ($x == 3) break;

echo "The number is: $x <br>";

?>

</body>

</html>

PHP foreach Loop

The foreach loop - Loops through a block of code for each element in an array or each property in an
object.

The most common use of the foreach loop, is to loop through the items of an array.

<html>

<body>

<?php

$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $x) {

echo "$x <br>";

?>

</body>

</html>

What is an Array?

An array is a special variable that can hold many values under a single name, and you can access the
values by referring to an index number or name.

<html>
<body>

<pre>

<?php

$cars = array("Volvo", "BMW", "Toyota");

var_dump($cars);

?>

</pre>

</body>

</html>

Output

array(3) {

[0]=>

string(5) "Volvo"

[1]=>

string(3) "BMW"

[2]=>

string(6) "Toyota"

The var_dump() function in PHP is used to display structured information about one or more
variables, including its type and value. Arrays and objects are explored recursively with values
indented to show structure

PHP Array Types

In PHP, there are three types of arrays:

 Indexed arrays - Arrays with a numeric index

 Associative arrays - Arrays with named keys

 Multidimensional arrays - Arrays containing one or more arrays

Array Items
 Array items can be of any data type.
 The most common are strings and numbers (int, float), but array items
can also be objects, functions or even arrays.
 You can have different data types in the same array
Indexed Array

<html>

<body>

<?php

$cars = array("Volvo", "BMW", "Toyota");

echo $cars[0];

?>

</body>

</html>

Change Value

To change the value of an array item, use the index number:

<html>

<body>

<pre>

<?php

$cars = array("Volvo", "BMW", "Toyota");

$cars[1] = "Ford";

var_dump($cars);

?>

</pre>

</body>

</html>

Loop Through an Indexed Array

To loop through and print all the values of an indexed array, you could use a foreach loop

<html>

<body>
<?php

$cars = array("Volvo", "BMW", "Toyota");

foreach ($cars as $x) {

echo "$x <br>";

?>

</body>

</html>

Index Number

The key of an indexed array is a number, by default the first item is 0 and the second is 1 etc., but
there are exceptions.

array_push() function to add a new item

<html>

<body>

<pre>

<?php

$cars[0] = "Volvo";

$cars[1] = "BMW";

$cars[2] = "Toyota";

array_push($cars, "Ford");

var_dump($cars);

?>

</pre>

</body>

</html>

Ex.2

<html>

<body>

<p>The next array item gets the index 15:</p>


<pre>

<?php

$cars[5] = "Volvo";

$cars[7] = "BMW";

$cars[14] = "Toyota";

array_push($cars, "Ford");

var_dump($cars);

?>

</pre>

</body>

</html>

PHP Associative Arrays

Associative arrays are arrays that use named keys that you assign to them.

<html>

<body>

<pre>

<?php

$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);

var_dump($car);

?>

</pre>

</body>

</html>

Output

array(3) {

["brand"]=>

string(4) "Ford"

["model"]=>

string(7) "Mustang"
["year"]=>

int(1964)

Access Associative Arrays

To access an array item you can refer to the key name.

<html>

<body>

<?php

$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);

echo $car["model"];

?>

</body>

</html>

Change Value

To change the value of an array item, use the key name:

<html>

<body>

<pre>

<?php

$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);

$car["year"] = 2024;

var_dump($car);

?>

</pre>
</body>

</html>

Loop Through an Associative Array

To loop through and print all the values of an associative array, you could use a foreach loop

<html>

<body>

<?php

$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);

foreach ($car as $x => $y) {

echo "$x: $y <br>";

?>

</body>

</html>

Add array item

<html>

<body>

<pre>

<?php

$fruits = array("Apple", "Banana", "Cherry");

$fruits[] = "Orange";
//Output the array:

var_dump($fruits);

?>

</pre>

</body>

</html>

Remove Array Item

To remove an existing item from an array, you can use the array_splice() function.

With the array_splice() function you specify the index (where to start) and how many items you want
to delete

<html>

<body>

<pre>

<?php

$cars = array("Volvo", "BMW", "Toyota");

array_splice($cars, 1, 1);

var_dump($cars);

?>

</pre>

</body>

</html>

Using the unset Function

You can also use the unset() function to delete existing array items.

Note: The unset() function does not re-arrange the indexes, meaning that after deletion the array
will no longer contain the missing indexes.

Remove Multiple Array Items

$cars = array("Volvo", "BMW", "Toyota");

array_splice($cars, 1, 2);
The unset() function takes a unlimited number of arguments, and can therefore be used to delete
multiple array items

$cars = array("Volvo", "BMW", "Toyota");

unset($cars[0], $cars[1]);

Remove Item From an Associative Array

To remove items from an associative array, you can use the unset() function

$cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964);

unset($cars["model"]);

Using the array_diff Function

You can also use the array_diff() function to remove items from an associative array.

This function returns a new array, without the specified items.

<html>

<body>

<pre>

<?php

$cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964);

$newarray = array_diff($cars, ["Mustang", 1964]);

var_dump($newarray);

?>

</pre>

</body>

</html>

Remove the Last Item

The array_pop() function removes the last item of an array.

$cars = array("Volvo", "BMW", "Toyota");

array_pop($cars);

Remove the First Item

The array_shift() function removes the first item of an array.

$cars = array("Volvo", "BMW", "Toyota");

array_shift($cars);
PHP - Sort Functions For Arrays

 sort() - sort arrays in ascending order

 rsort() - sort arrays in descending order

 asort() - sort associative arrays in ascending order, according to the value

 ksort() - sort associative arrays in ascending order, according to the key

 arsort() - sort associative arrays in descending order, according to the value

 krsort() - sort associative arrays in descending order, according to the key

Sort Array in Ascending Order - sort()


$cars = array("Volvo", "BMW", "Toyota");

sort($cars);

PHP - Multidimensional Arrays

PHP supports multidimensional arrays that are two, three, four, five, or more levels deep.

The dimension of an array indicates the number of indices you need to select an element.

 For a two-dimensional array you need two indices to select an element

 For a three-dimensional array you need three indices to select an element

PHP - Two-dimensional Arrays


A two-dimensional array is an array of arrays (a three-dimensional array is an
array of arrays of arrays).

Name Stock Sold

Volvo 22 18

BMW 15 13

Saab 5 2

Land Rover 17 15
$cars = array (

array("Volvo",22,18),

array("BMW",15,13),

array("Saab",5,2),

array("Land Rover",17,15)

);

echo $cars[0][0].": In stock: ".$cars[0][1].", sold: ".$cars[0][2].".<br>";

echo $cars[1][0].": In stock: ".$cars[1][1].", sold: ".$cars[1][2].".<br>";

echo $cars[2][0].": In stock: ".$cars[2][1].", sold: ".$cars[2][2].".<br>";

echo $cars[3][0].": In stock: ".$cars[3][1].", sold: ".$cars[3][2].".<br>";

for ($row = 0; $row < 4; $row++) {

echo "<p><b>Row number $row</b></p>";

echo "<ul>";

for ($col = 0; $col < 3; $col++) {

echo "<li>".$cars[$row][$col]."</li>";

echo "</ul>";

PHP Strings

Double quoted strings perform action on special characters.

$x = "John";

echo "Hello $x";

Single quoted string literals returns the string as it is:

$x = "John";

echo 'Hello $x'; -- OUTPUT IS SAME Hello $x

String Length - echo strlen("Hello world!");


Word Count

echo str_word_count("Hello world!");

Search For Text Within a String

echo strpos("Hello world!", "world");

output: 6 (Starting position of the searching word)

Upper Case

$x = "Hello World!";

echo strtoupper($x);

Lower Case

$x = "Hello World!";

echo strtolower($x);

Replace String

$x = "Hello World!";

echo str_replace("World", "Dolly", $x);

Reverse a String

$x = "Hello World!";

echo strrev($x);

Remove Whitespace

$x = " Hello World! ";

echo trim($x);

Convert String into Array


$x = "Hello World!";

$y = explode(" ", $x);

//Use the print_r() function to display the result:

print_r($y);

/*

Result:

Array ( [0] => Hello [1] => World! )

*/

You might also like