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

6. Arrays

Uploaded by

sachin248124
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
28 views

6. Arrays

Uploaded by

sachin248124
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 45

PHP ARRAYS

Presented By:-
Er. Yatika Hasija
Assistant Professor
Department of Computer Science
Lovely Professional University
PHP arrays
• Arrays are complex variables that allow us to store more
than one value or a group of values under a single
variable name.
• An array stores multiple values in one single
variable.

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


//Declaring Arrays
Types of Arrays in PHP
There are three types of arrays that you can create. These
are:

• Indexed array — An array with a numeric key.


• Associative array — An array where each key has its
own specific value i.e Arrays with named keys
• Multidimensional array — An array containing one or
more arrays within itself.
Indexed Arrays
• An indexed or numeric array stores each array element with a
numeric index.

<?php
$courses = array("PHP", "Laravel", "Node js");
echo "I like " . $courses[0] . ", " . $courses[1] . " and " .
$courses[2];
echo "<br>";
echo count($courses);
?>
OUTPUT:
I like PHP, Laravel and Node js
3
Working With Arrays
• Create Arrays
• Access Arrays
• Update Arrays
• Add Array Items
• Remove Array Items
• Sort Arrays
Create Array

You can create arrays by using the array() function:


$cars = array("Volvo", "BMW", "Toyota");
Short syntax by using the [] brackets:
$cars = ["Volvo", "BMW", "Toyota"];
Multiple Lines
Line breaks are not important, so an array declaration can
span multiple lines:

$cars = [
"Volvo",
"BMW",
"Toyota"
];
Trailing Comma

A comma after the last item is allowed:


$cars = [
"Volvo",
"BMW",
"Toyota",
];
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:

$cars = [
0 => "Volvo",
1 => "BMW",
2 =>"Toyota"
];
Associative Arrays
Indexed arrays are the same as associative arrays, but
associative arrays have names instead of numbers:

$myCar = [
"brand" => "Ford",
"model" => "Mustang",
"year" => 1964
];
Declare Empty Array

You can declare an empty array first, and add items to it


later:
$cars = [];
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
Associative arrays
• The same goes for associative arrays, you can declare
the array first, and then add items to it:
$myCar = [];
$myCar["brand"] = "Ford";
$myCar["model"] = "Mustang";
$myCar["year"] = 1964;
Mixing Array Keys

You can have arrays with both indexed and named keys:
$myArr = [];
$myArr[0] = "apples";
$myArr[1] = "bananas";
$myArr["fruit"] = "cherries";
Access Array Item

• To access an array item, you can refer to the index


number for indexed arrays, and the key name for
associative arrays.

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


echo $cars[2];
To access items from an associative array, use
the key name:
$cars = array("brand" => "Ford", "model" => "Mustang",
"year" => 1964);
echo $cars["year"];
Double or Single Quotes

• You can use both double and single quotes when


accessing an array

echo $cars["model"];
echo $cars['model'];
Excecute a Function Item
Array items can be of any data type, including function.

To execute such a function, use the index number followed


by parentheses ():

function myFunction() {
echo "I come from a function!";
}
$myArr = array("Volvo", 15, myFunction);
$myArr[2]();
Use the key name when the function is an item in
a associative array:
function myFunction() {
echo "I come from a function!";
}

$myArr = array("car" => "Volvo", "age" => 15, "message" =>


myFunction);

$myArr["message"]()
Loop Through an Indexed Array(for loop)
<?php
$courses = array("PHP", "Laravel", "Node js");
$courseslength = count($courses); //can use sizeof()

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


echo $courses[$x];
echo "<br>";
}
?>
OUTPUT:
PHP
Laravel
Node js
Loop Through an Indexed Array(PHP foreach
Loop)
• The foreach loop is used to iterate over arrays.
• It is used to loop through each key/value pair in an array.
<?php
$courses = array("PHP", "Laravel", "Node js");

// Loop through colors array


foreach($courses as $course){
echo $course . "<br>";
}
?>

OUTPUT:
PHP
Laravel
Node js
Loop Through an Indexed Array

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


foreach ($cars as $x) {
echo "$x <br>";
}
Loop Through an Associative Array

To loop through and print all the values of an associative


array, you can use a foreach loop, like this:

$car = array("brand"=>"Ford", "model"=>"Mustang",


"year"=>1964);
foreach ($car as $x => $y) {
echo "$x: $y <br>";
}
Associative Array
• Associative arrays are arrays that use named keys that
you assign to them.

• We can associate name with each array elements in PHP


using => symbol.

• The keys assigned to values can be arbitrary and user


defined strings.
Associative Array(contd.)
<?php
$courses = array("INT220"=>"PHP", "INT221"=>"Laravel",
"INT222"=>"Node js");
echo "INT 220 is ".$courses['INT220'].". INT 221 is ".
$courses['INT221'].". INT222 is ".$courses['INT222'];
?>
OUTPUT:
INT 220 is PHP. INT 221 is Laravel. INT222 is Node js
Associative Array(contd.)
<?php
$courses["INT220"] = "PHP";
$courses["INT221"] = "Laravel";
$courses["INT222"] = "Node js";

// Printing array structure


print_r($courses); //Print the information about some
variables in a more human-readable way:
?>

OUTPUT:
Array ( [INT220] => PHP [INT221] => Laravel [INT222] => Node
js )
Loop Through an Associative Array(for each
loop)
<?php
$courses =
array("INT220"=>"PHP","INT221"=>"Laravel","INT222"=>"Node
js");
foreach($courses as $course => $value) {
echo "Key=".$course.","."Value=".$value;
echo "<br>";
}
?>
OUTPUT:
Key=INT220, Value=PHP
Key=INT221, Value=Laravel
Key=INT222, Value=Node js
Loop Through an Associative Array(for loop)
<?php
$courses = array('INT220'=>'PHP','INT221'=>'Laravel','INT222'=>
'Node js');
$keys = array_keys($courses);
$values = array_values($courses);
for($x=0; $x<count($courses); $x++) {
echo "Key=".$keys[$x].','."Value=".$values[$x]. "<br>";
}
?>
OUTPUT:
Key=INT220,Value=PHP
Key=INT221,Value=Laravel
Key=INT222,Value=Node js
PHP Update Array Items

To update an existing array item, you can refer to the index


number for indexed arrays, and the key name for
associative arrays.

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


$cars[1] = "Ford";
To update items from an associative array, use
the key name:
$cars = array("brand" => "Ford", "model" => "Mustang",
"year" => 1964);
$cars["year"] = 2024;
Add Array Item

• To add items to an existing array, you can use the bracket


[] syntax.

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


$fruits[] = "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

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


$cars["color"] = "Red";
Add Multiple Array Items

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


array_push($fruits, "Orange", "Kiwi", "Lemon");
print_r($fruits);// The array_push() function inserts one
or more elements to the end of an array.
Add Multiple Items to Associative Arrays

To add multiple items to an


existing array, you can use
the += operator.
$cars = array("brand" => "Ford", "model" =>
"Mustang");
$cars += ["color" => "red", "year" => 1964];
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.

<?php
$cars = array("Volvo", "BMW", "Toyota");
array_slice($cars, 1, 1); //If want to remove an element without
causing gaps in the indexes
var_dump($cars);
?>

After the deletion, the array gets reindexed automatically, starting


at index 0.
Multidimensional Arrays
• The multidimensional array is an array in which each
element can also be an array and each element in the
sub-array can be an array or further contain array within
itself and so on.
Multidimensional Arrays(contd.)
OUTPUT:
<?php Manoj----CGPA is: 7.8 and his status is
$result = array( pass
array("Manoj",7.8,"pass"), Aditya----CGPA is: 8.5 and his status is
pass
array("Aditya",8.5,"pass"),
Anuj----CGPA is: 4.9 and his status is fail
array("Anuj",4.9,"fail")
);
echo $result[0][0]. "----CGPA is: " . $result[0][1]." and his status is ".
$result[0][2]."<br>";
echo $result[1][0]. "----CGPA is: " . $result[1][1]." and his status is ".
$result[1][2]."<br>";
echo $result[2][0]. "----CGPA is: " . $result[2][1]." and his status is ".
$result[2][2];
?>
Multidimensional Arrays(contd.)
<?php
$result = array(
array(
"name" => "Manoj",
OUTPUT:
"cgpa" => 7.8, Manoj----CGPA is: 7.8 and his status is pass
),
"status" => "pass"
Aditya----CGPA is: 8.5 and his status is pass
array( Anuj----CGPA is: 4.9 and his status is fail
"name" => "Aditya",
"cgpa" => 8.5,
"status" => "pass"
),
array(
"name" => "Anuj",
"cgpa" => 4.9,
"status" => "fail"
)
);
echo $result[0]["name"]. "----CGPA is: " . $result[0]["cgpa"]." and his status is ".$result[0]["status"]."<br>";
echo $result[1]["name"]. "----CGPA is: " . $result[1]["cgpa"]." and his status is ".$result[1]["status"]."<br>";
echo $result[2]["name"]. "----CGPA is: " . $result[2]["cgpa"]." and his status is ".$result[2]["status"];
?>
Loop Through an Multidimensional Array(for
loop)
<?php
$result = array ( OUTPUT:

array("Manoj",7.8,"pass"),
array("Aditya",8.5,"pass"), Row number 0
Manoj
array("Anuj",4.9,"fail") 7.8
Pass
);
Row number 1
Aditya
for ($row = 0; $row < 3; $row++) { 8.5
echo "<h4>Row number $row</h4>"; Pass

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


echo $result[$row][$col]."<br>"; Anuj
4.9
}
fail
}
?>
Loop Through an Multidimensional
Array(foreach loop)
<?php
OUTPUT:
$result = array (
array("Manoj",7.8,"pass"),
Row number 0
array("Aditya",8.5,"pass"),
Manoj
array("Anuj",4.9,"fail") 7.8
); Pass

for($row = 0; $row < 3; $row++) { Row number 1


echo "<h4>Row number $row</h4>"; Aditya
8.5
Pass
foreach ($result[$row] as $resul) {
Row number 2
echo $resul."<br>"; Anuj
} 4.9
fail
}
?>
Loop Through an Multidimensional
Array(foreach loop)
<?php
$books =
array("C++" => array("name" => "Beginning with C","copies" =>8),
"PHP" => array("name" => "Basics of PHP","copies" => 10),
"Laravel" => array("name" => "MVC","copies" => 3)
); C++
name = Beginning with C
copies = 8
$keys = array_keys($books);
for($i = 0; $i < count($books); $i++) { PHP
echo "<h1>$keys[$i]</h1>"; name = Basics of PHP
copies = 10
foreach($books[$keys[$i]] as $key => $value) {
echo $key . " = " . $value . "<br>"; Laravel
} name = MVC
copies = 3
}
?>
Enums
• Enums allow you to define a set of named constants
that represent a finite list of possible values for a
variable.
enum
consider that you are building a web application that
allows customers to order coffee online, you can use an
enum to represent the different sizes of coffee that
customers can order.

enum CoffeeSize {
SMALL,
MEDIUM,
LARGE
};
• In this example, we define
an enum called CoffeeSize that represents the size of a
coffee. The enum has three constants: SMALL,
MEDIUM, and LARGE.

$coffeeSize = CoffeeSize::MEDIUM;

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy