Unit 2 PHP-1
Unit 2 PHP-1
PHP Arrays
An array stores multiple values in one single variable:
Example
$cars = array("Volvo", "BMW", "Toyota");
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.
Create Arrays
Access Arrays
Update Arrays
Add Array Items
Remove Array Items
Sort 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.
Example
Array items of four different data types:
<!DOCTYPE html>
<html>
<body>
<?php
// function example:
function myFunction() {
echo "This text comes from a function";
}
// create array:
$myArr = array("Volvo", 15, ["apples", "bananas"], myFunction);
Array Functions
The real strength of PHP arrays are the built-in array functions, like
the count() function for counting array items:
Example
How many items are in the $cars array:
echo count($cars);
By default, the first item has index 0, the second item has item 1, etc.
Example
Create and display an indexed array:
var_dump($cars);
array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
}
echo $cars[0];
Volvo
Change Value
To change the value of an array item, use the index number:
Example
Change the value of the second item:
$cars[1] = "Ford";
var_dump($cars);
array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(4) "Ford"
[2]=>
string(6) "Toyota"
}
Example
Display all array items:
Volvo
BMW
Toyota
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.
New items get the next index number, meaning one higher than the highest
existing index.
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
And if you use the array_push() function to add a new item, the new item will get
the index 3:
Example
array_push($cars, "Ford");
var_dump($cars);
array(4) {
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
[3]=>
string(4) "Ford"
}
But if you have an array with random index numbers, like this:
$cars[5] = "Volvo";
$cars[7] = "BMW";
$cars[14] = "Toyota";
And if you use the array_push() function to add a new item, what will be the
index number of the new item?
Example
array_push($cars, "Ford");
var_dump($cars);
array(4) {
[5]=>
string(5) "Volvo"
[7]=>
string(3) "BMW"
[14]=>
string(6) "Toyota"
[15]=>
string(4) "Ford"
}
Example
$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
var_dump($car);
array(3)
{
["brand"]=>
string(4) "Ford"
["model"]=>
string(7) "Mustang"
["year"]=>
int(1964)
}
Example
Display the model of the car:
echo $car["model"];
Mustang
Change Value
To change the value of an array item, use the key name:
Example
Change the year item:
$car["year"] = 2024;
var_dump($car);
array(3) {
["brand"]=>
string(4) "Ford"
["model"]=>
string(7) "Mustang"
["year"]=>
int(2024)
}
Loop Through an Associative Array
To loop through and print all the values of an associative array, you could use
a foreach loop, like this:
Example
Display all array items, keys and values:
brand: Ford
model: Mustang
year: 1964
Array Keys
When creating indexed arrays the keys are given automatically, starting at 0
and increased by 1 for each item, so the array above could also be created with
keys:
Example
$cars = [
0 => "Volvo",
1 => "BMW",
2 =>"Toyota"
];
array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
}
As you can see, indexed arrays are the same as associative arrays, but
associative arrays have names instead of numbers:
Example
$myCar = [
];
array(3) {
["brand"]=>
string(4) "Ford"
["model"]=>
string(7) "Mustang"
["year"]=>
int(1964)
}
Example
$cars = [];
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(3) "BMW"
[2]=>
string(6) "Toyota"
}
The same goes for associative arrays, you can declare the array first, and then
add items to it:
Example
$myCar = [];
$myCar["brand"] = "Ford";
$myCar["model"] = "Mustang";
$myCar["year"] = 1964;
array(3) {
["brand"]=>
string(4) "Ford"
["model"]=>
string(7) "Mustang"
["year"]=>
int(1964)
}
Example
$myArr = [];
$myArr[0] = "apples";
$myArr[1] = "bananas";
$myArr["fruit"] = "cherries";
array(3) {
[0]=>
string(6) "apples"
[1]=>
string(7) "bananas"
["fruit"]=>
string(8) "cherries"
}
Example
Access an item by referring to its index number:
echo $cars[2];
Toyota
Example
Access an item by referring to its key name:
echo $cars["year"];
1964
To execute such a function, use the index number followed by parentheses ():
Example
Execute a function item:
function myFunction() {
$myArr[2]();
Use the key name when the function is an item in a associative array:
Example
Execute function by referring to the key name:
function myFunction() {
$myArr["message"]();
brand: Ford
model: Mustang
year: 1964
Example
Display all array items:
Volvo
BMW
Toyota
$cars[1] = "Ford";
array(3) {
[0]=>
string(5) "Volvo"
[1]=>
string(4) "Ford"
[2]=>
string(6) "Toyota"
}
Example
Update the year to 2024:
$cars["year"] = 2024;
array(3) {
["brand"]=>
string(4) "Ford"
["model"]=>
string(7) "Mustang"
["year"]=>
int(2024)
}
One way is to insert the & character in the assignment to assign the item value
by reference, and thereby making sure that any changes done with the array
item inside the loop will be done to the original array:
Example
Change ALL item values to "Ford":
$x = "Ford";
unset($x);
var_dump($cars);
array(3) {
[0]=>
string(4) "Ford"
[1]=>
string(4) "Ford"
[2]=>
string(4) "Ford"
}
To demonstrate this, see what happens when we change the value of $x after
the foreach loop:
Example
Demonstrate the consequence of forgetting the unset() function:
$x = "Ford";
$x = "ice cream";
var_dump($cars);
array(3) {
[0]=>
string(4) "Ford"
[1]=>
string(4) "Ford"
[2]=>
&string(9) "ice cream"
}
Example
Add one more item to the fruits array:
$fruits[] = "Orange";
array(4) {
[0]=>
string(5) "Apple"
[1]=>
string(6) "Banana"
[2]=>
string(6) "Cherry"
[3]=>
string(6) "Orange"
}
Associative Arrays
To add items to an associative array, or key/value array, use brackets [] for the
key, and assign value with the = operator.
Example
Add one item to the car array:
$cars = array("brand" => "Ford", "model" => "Mustang");
$cars["color"] = "Red";
array(3) {
["brand"]=>
string(4) "Ford"
["model"]=>
string(7) "Mustang"
["color"]=>
string(3) "Red"
}
Example
Add three item to the fruits array:
array(6) {
[0]=>
string(5) "Apple"
[1]=>
string(6) "Banana"
[2]=>
string(6) "Cherry"
[3]=>
string(6) "Orange"
[4]=>
string(4) "Kiwi"
[5]=>
string(5) "Lemon"
}
array(4) {
["brand"]=>
string(4) "Ford"
["model"]=>
string(7) "Mustang"
["color"]=>
string(3) "red"
["year"]=>
int(1964)
}
However, sometimes you want to store values with more than one key. For
this, we have multidimensional arrays.
PHP supports multidimensional arrays that are two, three, four, five, or more
levels deep. However, arrays more than three levels deep are hard to manage
for most people.
Volvo 22 18
BMW 15 13
Saab 5 2
Land Rover 17 15
<?php
$cars = array (
array("Volvo",22,18),
array("BMW",15,13),
array("Saab",5,2),
array("Land Rover",17,15)
);
?>
Volvo: In stock: 22, sold: 18.
BMW: In stock: 15, sold: 13.
Saab: In stock: 5, sold: 2.
Land Rover: In stock: 17, sold: 15.
We can also put a for loop inside another for loop to get the elements of the
$cars array (we still have to point to the two indices):
echo "<ul>";
echo "<li>".$cars[$row][$col]."</li>";
echo "</ul>";
<?php
// dimensional array
array(
array(1, 2),
array(3, 4),
),
array(
array(5, 6),
array(7, 8),
),
);
print_r($myarray);
?>
Note: The implode() function accept its parameters in either order. However, for
consistency with explode(), you should use the documented order of arguments.
Syntax
implode(separator,array)
<?php
$arr = array('Hello','World!','Beautiful','Day!');
echo implode(" ",$arr);
?>
O/P
Parameter Values
Parameter Description
<?php
$arr = array('Hello','World!','Beautiful','Day!');
echo implode("+",$arr)."<br>";
echo implode("-",$arr)."<br>";
echo implode("X",$arr);
?>
Syntax
explode(separator,string,limit)
Parameter Values
Parameter Description
Possible values:
<?php
$str = "Hello world. It's a beautiful day.";
print_r (explode(" ",$str));
?>
O/P
Array ( [0] => Hello [1] => world. [2] => It's [3] => a [4] => beautiful [5] => day. )
<?php
$str = 'one,two,three,four';
// zero limit
print_r(explode(',',$str,0));
// positive limit
print_r(explode(',',$str,2));
// negative limit
print_r(explode(',',$str,-1));
?>
O/P
Syntax
array_flip(array)
Example
Flip all keys with their associated values in an array:
<?php
$a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
$result=array_flip($a1);
print_r($result);
?>
O/P
Create a Function
A user-defined function declaration starts with the keyword function, followed by
the name of the function:
Call a Function
To call the function, just write its name followed by parentheses ():
Example
function myMessage() {
myMessage();
familyName("Jani");
familyName("Hege");
familyName("Hege", "1975");
familyName("Stale", "1978");
setHeight(350);
setHeight(135);
setHeight(80);
$z = $x + $y;
return $z;
5 + 10 = 15
7 + 13 = 20
2+4=6
function add_five(&$value) {
$value += 5;
$num = 2;
add_five($num);
echo $num;
$n = 0;
$len = count($x);
$n += $x[$i];
return $n;
$a = sumMyNumbers(5, 2, 6, 2, 7, 7);
echo $a;
29
Syntax:
$anonymousFunction = function($arg1, $arg2, ...) {
// Function body
};
Important Points
Anonymous functions are declared using the function keyword followed
by the list of parameters and the function body.
They can capture variables from the surrounding scope using
the use keyword.
Anonymous functions can be assigned to variables, passed as arguments
to other functions, or returned from other functions.
Usage
Inline Definition: Anonymous functions can be defined directly within the
code, eliminating the need for named function declarations.
Flexibility: They can be used as callbacks or event handlers where a
small, reusable function is required.
Closure Scope: Anonymous functions can access variables from the
enclosing scope using the use keyword, allowing for the encapsulation of
data.
Example:
// Define and use an anonymous function
$sum = function($a, $b) {
return $a + $b;
};
// Output: 5
echo $sum(2, 3);
Variable functions
if a variable name has parentheses appended to it, PHP will look for a function with
the same name as whatever the variable evaluates to, and will attempt to execute
it. Among other things, this can be used to implement callbacks, function tables,
and so forth.
String functions
Syntax
str_word_count(string,return,char)
<?php
echo str_word_count("Hello world!");
?>
Syntax
strlen(string)
<?php
echo strlen("Hello");
?>
Syntax
strrev(string)
<?php
echo strrev("Hello World!");
?>
!dlroW olleH
Related functions:
Syntax
strrpos(string,find,start)
Parameter Description
Find the position of the last occurrence of "php" inside the string:
<?php
echo strrpos("I love php, I love php too!","php");
?>
19
Parameter Description
Replace the characters "world" in the string "Hello world!" with "Peter":
<?php
echo str_replace("world","Peter","Hello world!");
?>
Hello Peter!
Related functions:
Syntax
ucwords(string, delimiters)
Parameter Values
Parameter Description
<?php
echo ucwords("hello world");
?>
Hello World
<?php
?>
Hello|World
<?php
Syntax:
int imagecolorallocate ( $image, $red, $green, $blue )
header("Content-Type: image/png");
imagepng($image);
imagedestroy($image);
?>
<?php
header("Content-type: image/png");
imagepng($image);
// Free memory
imagedestroy($image);
?>
You need to download the FPDF class from the FPDF website and
include it in your PHP script.
require('fpdf/fpdf.php');
Instantiate and use the FPDF class according to your need as shown in
the following examples.
$pdf=new FPDF();
<?php
ob_end_clean();
require('fpdf/fpdf.php');
$pdf->AddPage();
// Set the font for the text
$pdf->Cell(60,20,'Hello GeeksforGeeks!');
$pdf->Output();
?>