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

ArrayMethods.php

The document provides an overview of multidimensional arrays in PHP, explaining their structure and how to access elements using indices. It also covers various array manipulation functions such as extract(), compact(), array_flip(), and others, detailing their syntax and usage through examples. Additionally, it discusses methods for modifying, deleting, and sorting arrays.

Uploaded by

harshada Adhav
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

ArrayMethods.php

The document provides an overview of multidimensional arrays in PHP, explaining their structure and how to access elements using indices. It also covers various array manipulation functions such as extract(), compact(), array_flip(), and others, detailing their syntax and usage through examples. Additionally, it discusses methods for modifying, deleting, and sorting arrays.

Uploaded by

harshada Adhav
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 43

PHP - Multidimensional Arrays

• A multidimensional array is an array containing one or more arrays.


• 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

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) );

To get access to the elements of the $cars array we must point to the two indices (row
and column):
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>";
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):
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>";
}
o/p
O/p
Array Manipulation Functions
• extract()
• Compact()
• array_flip()
• list()
• array_slice()
• array_chunk()
• Implode()
• Explode()
• Array_keys()
• Array_values()
• Array_key_exist()
Compact()
• Compact() function works opposite to extract() function,the function
converts a group of variables into an array
• Syntax:
• Compact(var1,var2,….,…);
• Where var1,var2,…… are previously defined variables
Compact() example
<html>
<head><title></title></head>
<body>
<?php Output
$rollno=1;
Array ( [rollno] => 1
$name="Sachin"; [name] => Sachin
$city="Pune"; [city] => Pune )
$studinfo=compact("rollno","name","city");
echo "<pre>";
print_r($studinfo);
echo "</pre>";?>
</body>
</html>
PHP extract() Function
• This function uses array keys as variable names and values as variable
values.
• For each element it will create a variable in the current symbol table.
• This function returns the number of variables extracted on success.
Syntax
extract(array, extract_rules, prefix)
Parameter Values
Parameter Description

1. array Required. Specifies the array to use

2. extract_rules Optional. The extract() function checks for invalid variable names and collisions with
existing variable names. This parameter specifies how invalid and colliding names are
treated.Possible values:
•EXTR_OVERWRITE - Default. On collision, the existing variable is overwritten
•EXTR_SKIP - On collision, the existing variable is not overwritten
•EXTR_PREFIX_SAME - On collision, the variable name will be given a prefix
•EXTR_PREFIX_ALL - All variable names will be given a prefix

3. prefix Optional. If EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID or


EXTR_PREFIX_IF_EXISTS are used in the extract_rules parameter, a specified prefix is
required.

This parameter specifies the prefix. The prefix is automatically separated from the
array key by an underscore character.
extract() example
<?php
$id=12;
$job="Worker";
$emp=array("id"=>123,
printing v prefixed variables
"name"=>"Sai", 123
"job"=>"manager"); Sai
manager
extract($emp,EXTR_PREFIX_ALL,"v");
echo" <br><b>printing v prefixed variables<b><br>";
echo $v_id."<br> $v_name<br>$v_job";

?>
array_flip()
• Definition and Usage
• The array_flip() function flips/exchanges all keys with their associated
values in an array.
Syntax
• array_flip(array)

Parameter Description

array Required. Specifies an array of key/value pairs to be flipped


# Example array_flip()
<?php
$Emp=array("id"=>"100", foreach ($Emp as $k=>$v)
{
"name"=>"Sahil",
echo " $k=> $v <br>";
"city"=>"Pune"); }
$empflip=array_flip($Emp); echo "<br>";
foreach ($empflip as $k=>$v)
{
echo " $k=> $v <br>";
}
?>
list()
Definition and Usage
The list() function is used to assign values to a list of variables in one
operation.
Syntax
list(var1, var2, ...)=$arr1

Parameter Description

var1 Required. The first variable to assign a value to

var2,... Optional. More variables to assign values to


Example
//copies values of array in variables
<?php
$cars=array("Toyata","Volvo","BMW");
list($car1,$car2,$car3)=$cars; //Copy values of array in variable
echo "<br> $car1";
echo "<br> $car2";
echo "<br> $car3";
?>
PHP array_slice() Function
Definition and Usage
• The array_slice() function returns selected parts of an array.
Syntax
• array_slice(array, start, length, preserve)
• Note: If the array have string keys, the returned array will always preserve
the keys
array Required. Specifies an array

start Required. Numeric value. Specifies where the function will start the
slice(index value)
length Optional. Numeric value. Specifies the length of the returned array.

preserve •Optional. Specifies if the function should preserve or reset the


keys.
•Possible values:true –
•Preserve keys
•false - Default. Reset keys
Example : array_slice() method
<?php
$list=array("john","jonhy","janardan");
$list1=array_slice($list,0,2);
print_r($list);
echo "<br>";
print_r($list1);
?>
PHP array_chunk() Function
Definition and Usage
• The array_chunk() function splits an array into chunks of new arrays.
Syntax
• array_chunk(array, size, preserve_key)
Parameter Values
Parameter Description
array Required. Specifies the array to use
size Required. An integer that specifies the size of each
chunk
preserve_k •Optional. Possible values:
ey •true – Preserves the keys
false – Default. Re indexes the chunk numerically
Example array_chunk() Function

<?php
$cars=array("Volvo","BMW","Toyota","Honda","Mercedes","Opel");
print_r(array_chunk($cars,2));
?>
Output->
Array ( [0] => Array ( [0] => Volvo [1] => BMW ) [1] => Array ( [0] =>
Toyota [1] => Honda ) [2] => Array ( [0] => Mercedes [1] => Opel ) )

Return Returns a multidimensional indexed array, starting with


Value: zero, with each dimension containing size elements
implode
• The implode() function returns a string from the elements of an array.
Syntax
implode(separator,array)
Parameter
Parameter Description
separator Optional. Specifies what to put between the array elements.
Default is "" (an empty string)
array Required. The array to join to a string
Example
<?php Array
(
[0] => Sachin
$students=array("Sachin","Sahil","Sehvag","Vedant","Priti"); [1] => Sahil
echo "<pre>"; [2] => Sehvag
print_r($students); [3] => Vedant
[4] => Priti
)

$snames=implode(",", $students); Sachin,Sahil,Sehvag,Vedant,Priti

echo"<br>";
print_r($snames);
echo "</pre>";

?>
explode
• The explode() function is an inbuilt function in PHP used to split a
string into different strings.
• The explode() function splits a string based on a string delimiter, i.e.
this function returns an array containing the strings formed by
splitting the original string.
Syntax:
explode(separator, OriginalString)
Example

<?php

$list=array("john","jonhy","janardan");
$values=implode(",", $list); //$values is String now
echo($values);
echo "<br>";
$arr=explode(",",$values);
print_r( $arr);
john,jonhy,janardan
Array ( [0] => john [1] => jonhy [2] => janardan )
?>
Array_splice()
• Purpose- Array_splice() function eliminated selected elements from
array.
• It returns array of eliminated elements
• Syntax:
• Array_splice(array,start,length)
• Where array-input array
• start-index of array element to be removed
• length-integer values indicated number of elements
Example : array_splice()
<?php
$emp=
array("id"=>100,"name"=>"Anil","city"=>"Pune","job"=>"Manager");
echo "<pre>";
print_r($emp);
$empsplice=array_splice($emp,0,3);
echo" <br>";
print_r($empsplice);
echo "</pre>";
?>
Array_keys()
• Retrive all keys of an array.

<?php
$emp=
array("id"=>100,"name"=>"Anil","city"=>
"Pune","job"=>"Manager");
echo "<pre>";
print_r(array_keys($emp));
echo "</pre>";
?>
Array_values()
• Retrive all values of an array.

<?php
$emp=
array("id"=>100,"name"=>"Anil","city"=>
"Pune","job"=>"Manager");
echo "<pre>";
print_r(array_values($emp));
echo "</pre>";
?>
Array_key_exits()
• Array_key_exits() function is used to verify whether given key is
present in array or not.
• Syntax array_key_exists(array_key,array_name)
Example
<?php
$emp=
array("id"=>100,"name"=>"Anil","city"=>"Pune","job"=>"Manager");
echo "<pre>";
print_r($emp);
$check=array_key_exists('id',$emp);
if($check)
{
echo "id Key is Present";
}
else
{
echo "id Key is Not Present";
}
echo "</pre>";
?>
Modifying Data in Array
34

. 16/01/25
OutPut
Deleting Array element
Unset() function

. 16/01/25
Output
Sorting Array

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

. 16/01/25
sort() - sort arrays in ascending
order

16/01/25
Output:

16/01/25
Chap2. Arrays Functions and Graphics
41

 rsort() - sort arrays in descending order

. 16/01/25
Chap2. Arrays Functions and Graphics
42

 Output:

. 16/01/25

You might also like