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

76-PHP-Arrays and Array functions-10-10-2024 (1)

The document provides an overview of different types of arrays in PHP, including numeric, associative, and multidimensional arrays, along with examples of how to create and manipulate them. It also covers various array functions such as merging, sorting, and searching arrays, as well as using loops to iterate through array elements. Additionally, it explains the use of array operators and the functionality of specific array functions with practical examples.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

76-PHP-Arrays and Array functions-10-10-2024 (1)

The document provides an overview of different types of arrays in PHP, including numeric, associative, and multidimensional arrays, along with examples of how to create and manipulate them. It also covers various array functions such as merging, sorting, and searching arrays, as well as using loops to iterate through array elements. Additionally, it explains the use of array operators and the functionality of specific array functions with practical examples.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Arrays

 Numeric array - An array with a numeric index. Values are


stored and accessed in linear fashion.
 Associative array - An array with strings as index. This
stores element values in association with key values rather
than in a strict linear index order.
 Multidimensional array - An array containing one or
more arrays and values are accessed using multiple indices.
Numeric Array
<html> <body> /* Second method to create array.
<?php */
/* First method to create array. */ $num[0] = "one";
$numbers = array( 1, 2, 3, 4, 5); $num[1] = "two";
foreach( $numbers as $value ) $num[2] = "three";
{ foreach( $num as $value )
echo "Value is $value <br />"; { echo "Value is $value <br />";
} }
?>
</body> </html>
Associative array
/* First method to create array. */ /* Second method to create array.
$salaries = array( "Mohammad" => */
2000, "John" => 1000, "Kumar" $salaries['Mohammad'] = "high";
=> 500 ); $salaries['John'] = "medium";
echo "Salary of Mohammad is ". $salaries['Kumar'] = "low";
$salaries['Mohammad'] . "<br>"; echo "Salary of Mohammad is ".
echo "Salary of John is ". $salaries['Mohammad'] . "<br >";
$salaries['John']. "<br>"; echo "Salary of John is ".
echo "Salary of Kumar is ". $salaries['Kumar']. "<br>";
$salaries['Kumar']. "<br>";
Multidimensional Array
$marks = array( "mohammad" => array ( "physics" => 35, "maths"
=> 30, "chemistry" => 39 ), "john" => array ( 10,20,30 ),
"kumar" => array ( "physics" => 31, "maths" => 22, "chemistry" =>
39 ) );
/* Accessing multi-dimensional array values */
echo "Marks for mohammad in physics : " ;
echo $marks['mohammad']['physics'] . "<br />";
echo "Marks for john in maths : ";
echo $marks['john'][1] . "<br />"; //numerical array
echo "Marks for kumar in chemistry : " ;
echo $marks['kumar']['chemistry'] ; //associative array
Multidimensional arrays
$Student = array (
"0"=> array ("name"=>"James", "sex"=>"Male",
"age"=>"28"),
"1"=> array ("name"=>"John", "sex"=>"Male",
"age"=>"25"),
"2"=> array ("name"=>"Susan", "sex"=>"Female",
"age"=>"24"));

$student[“1"][“name"] – returns John


Array Operators
$x = array("a" => "red", "b" => "green");
$y = array("c" => "blue", "d" => "yellow");
$z = $x + $y; // union of $x and $y
$z  red,green,blue,yellow
$x == $y  false
$x === $y  false
$x != $y  true
$x <> $y  true
$x !== $y  true
foreach

 The foreach loop works only on arrays, and is used to loop


through each key/value pair in an array.
 <?php
$colors = array("red","green","blue","yellow");

foreach ($colors as $value) {


echo "$value <br>"; red
} green
blue
?> yellow
Array Functions

Array(key=>value) – Creates an array with keys and


values

E.g.:
<?php
$a=array("a"=>"Dog","b"=>"Cat","c"=>"Horse");
print_r($a);
?>

Output:
Array ( [a] => Dog [b] => Cat [c] => Horse )
Array Functions
array_chunk(array,size,preserve_key ) - splits an array
into chunks of new arrays

E.g.: 1
<?php
$a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse","d"=>"
Cow");
print_r(array_chunk($a,2));
?>

Output:
Array (
[0] => Array ( [0] => Cat [1] => Dog )
[1] => Array ( [0] => Horse [1] => Cow )
)
Array Functions
E.g.: 2
<?php
$a=array("a"=>"Cat","b"=>"Dog","c"=>"Horse","d"=>"
Cow");
print_r(array_chunk($a,2,true));
?>

Output:
Array (
[0] => Array ( [a] => Cat [b] => Dog )
[1] => Array ( [c] => Horse [d] => Cow )
)
Array Functions
array_combine(array1,array2) creates an array by combining
two other arrays, where the first array is the keys, and the other array
is the values.

E.g.:
<?php
Output:
$a1=array("a","b","c","d"); Array ( [a] => Cat [b] => Dog [c] =>
$a2=array("Cat","Dog","Horse","Cow"); Horse [d] => Cow )
print_r(array_combine($a1,$a2));
?>
Array Functions

array_count_values(array) returns an array, where the keys


are the original array's values, and the values is the number of
occurrences.

E.g:
<?php
Output:
$a=array("Cat","Dog","Horse","Dog"); Array ( [Cat] => 1 [Dog] => 2 [Horse] =>
print_r(array_count_values($a)); 1)
?>
Array Functions

array_diff(arr1,arr2,…) function compares two or more


arrays, and returns an array with the keys and values from the
first array, only if the value is not present in any of the other
arrays.

E.g:

<?php Output:
$a1=array(0=>"Cat",1=>"Dog",2=>"Horse");
$a2=array(3=>"Horse",4=>"Dog",5=>"Fish"); Array ( [0] => Cat )
print_r(array_diff($a1,$a2));
?>
Array Functions

The array_diff_assoc(arr1, arr2,…) function compares two or


more arrays, and returns an array with the keys and values from
the first array, only if they are not present in any of the other
arrays.

E.g:
<?php
$a1=array(0=>"Cat",1=>"Dog";,2=>"Horse");
Output:
$a2=array(0=>"Rat",1=>"Horse";,2=>"Dog"); Array ( [0] => Cat [2] => Horse
$a3=array(0=>"Horse",1=>"Dog",2=>"Cat"); )
print_r(array_diff_assoc($a1,$a2,$a3));
?>
Array Functions

array_fill(start,number,value ) function returns an array filled


with the values you describe

E.g:

<?php
Output:
$a=array_fill(2,3,"Dog"); Array ( [2] => Dog [3] => Dog
print_r($a); [4] => Dog )
?>
Array Functions

The array_flip(array ) function returns an array with all the


original keys as values, and all original values as keys.

E.g:

<?php
Output:
$a=array(0=>"Dog",1=>"Cat",2=>"Horse"); Array ( [Dog] => 0 [Cat] => 1
print_r(array_flip($a)); [Horse] => 2 )
?>
Array Functions

The array_key_exists(key,arr ) function checks an array for a


specified key, and returns true if the key exists and false is the
key does not exist.

E.g:
<?php
$a=array("a"=>"Dog","b"=>"Cat");
Output:
if (array_key_exists("a",$a))
echo "Key exists!"; Key exists!
else
echo "Key does not exist!";
?>
Array Functions

The array_merge(array1,array2,array3...) function merges


one ore more arrays into one array.

E.g:

<?php
Output:
$a1=array("a"=>"Horse","b"=>"Dog"); Array ( [a] => Horse [b] => Dog [c]
$a2=array("c"=>"Cow",“d"=>"Cat"); => Cow [d]=>Cat )
print_r(array_merge($a1,$a2));
?>
Array Functions

E.g:

<?php
$a=array(3=>"Horse",4=>"Dog");
print_r(array_merge($a));
?>

Output:
Array ( [0] => Horse [1] => Dog )
Array Functions

E.g:
<?php
$a1=array("Dog","Dog","Cat");
$a2=array("Pluto","Fido");
array_multisort($a1,SORT_ASC,$a2,SORT_DESC); print_r($a1);
print_r($a2);
?>

Output:
Array ( [0] => Cat [1] => Dog [2] => Dog )
Array ( [0] => Pluto [1] => Fido )
Array Functions

The array_pop(array) function deletes the last element of an array.


array_shift(array) – removes an element at the beginning of the array

E.g:
<?php
$a=array("Dog","Cat","Horse");
Output:
array_pop($a); Array ( [0] => Dog [1] => Cat )
print_r($a); Array ( [0] => Cat )
array_shift($a);
print_r($a);
?>
Array Functions

The array_push(array,value1,value2...) function inserts one or more


elements to the end of an array. array_unshift(array) – inserts an element
at the beginning of the array

E.g:
<?php
$a=array("Dog","Cat");
array_push($a,"Horse","Bird");
Print_r($a);
Output:
array_unshift($a, “fish”); Array ( [0] => Dog [1] => Cat [2] => Horse [3] => Bird )
Array ( [0] => fish [1]=>Dog [2] => Cat [3] => Horse [4] => Bird
print_r($a);
)
?>
Array Functions

Output ????????

E.g:

<?php
$a=array("a"=>"Dog","b"=>"Cat"); Output:
array_push($a,"Horse","Bird");
print_r($a); Array ( [a] => Dog [b] => Cat [0] =>
?> Horse [1] => Bird )
Array Functions

array_rand(array,num) function returns a random key from an array, or it


returns an array of random keys if you specify that the function should return more
than one key.

E.g:

<?php
$a=array("a"=>"Dog","b"=>"Cat","c"=>"Hors Output:
e");
print_r(array_rand($a,1)); b
?>
Array Functions

The array_reverse(array,preserve) function returns an array in the


reverse order.

E.g:

<?php
$a=array("a"=>"Dog","b"=>"Cat","c"=>"Hors Output:
e");
print_r(array_reverse($a)); Array ( [c] => Horse [b] => Cat [a] =>
?> Dog )
Array Functions

The array_search(value,array,strict ) function search an array for a value


and returns the key.

E.g:

<?php
$a=array("a"=>"Dog","b"=>"Cat","c"=>"Hors Output:
e");
echo array_search("Dog",$a); a
?>
Array Functions

The array_slice(array, start, length, preserve) function returns


selected parts of an array.

E.g:

<?php
$a=array(0=>"Dog",1=>"Cat",2=>"Horse",3= Output:
>"Bird");
print_r(array_slice($a,1,2)); Array ( [0] => Cat [1] => Horse )
?>
Array Functions

The array_splice(array,start,length,array) function removes selected


elements from an array and replaces it with new elements. The function also returns
an array with the removed elements.

E.g:
<?php
$a1=array(0=>"Dog",1=>"Cat",2=>"Horse",3
=>"Bird"); Output:
$a2=array(0=>"Tiger",1=>"Lion");
array_splice($a1,0,2,$a2); Array ( [0] => Tiger [1] => Lion [2] =>
print_r($a1); Horse [3] => Bird )
?>
Array Functions

The array_sum(array) function returns the sum of all the values in the array.

E.g:

<?php
$a=array(0=>"5",1=>"15",2=>"25"); Output:
echo array_sum($a);
?> 45
Sorting
 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
Sorting arrays -example
 Sort
$cars = array("Volvo", "BMW", "Toyota");
sort($cars);
$clength = count($cars);
for($x = 0; $x < $clength; $x++) {
echo $cars[$x];
echo "<br>";
}
 Sort numbers
$numbers = array(4, 6, 2, 22, 11);
sort($numbers);
$arrlength = count($numbers);
for($x = 0; $x < $arrlength; $x++) {
echo $numbers[$x];
echo "<br>";
}
Array Functions

The arsort(array,sorttype) function sorts an array by the values in reverse


order.The values keep their original keys.

E.g:
<?php Output:
$my_array = array("a" => "Dog", "b" => "Cat", Array
"c" => "Horse"); (
arsort($my_array); [c] => Horse
print_r($my_array); [a] => Dog
?> [b] => Cat
)
Array Functions

The asort(array,sorttype) function sorts an array by the values. The values


keep their original keys

E.g:
<?php Output:
$my_array = array("a" => "Dog", "b" => "Cat", Array
"c" => "Horse"); (
asort($my_array); [b] => Cat
print_r($my_array); [a] => Dog
?> [c] => Horse
)
Array Functions

The krsort(array,sorttype) function sorts an array by the keys in reverse


order.The values keep their original keys.

E.g:
<?php Output:
$my_array = array("a" => "Dog", "b" => "Cat", Array
"c" => "Horse"); (
krsort($my_array); [c] => Horse
print_r($my_array); [b] => Cat
?> [a] => Dog
)
Array Functions

The ksort(array,sorttype) function sorts an array by the keys. The values keep
their original keys.

E.g:
<?php Output:
$my_array = array("a" => "Dog", "b" => "Cat", Array
"c" => "Horse"); (
ksort($my_array); [a] => Dog
print_r($my_array); [b] => Cat
?> [c] => Horse
)
Array Functions

The rsort(array,sorttype) function sorts an array by the values in


reverse order. This function assigns new keys for the elements in the array. Existing
keys will be removed. This function returns TRUE on success, or FALSE on failure.

E.g:
<?php Output:
$my_array = array("a" => "Dog", "b" => "Cat", Array
"c" => "Horse"); (
rsort($my_array); [0] => Horse
print_r($my_array); [1] => Dog
?> [2] => Cat
)
Array Functions

The sort(array,sorttype) function sorts an array by the values. This function


assigns new keys for the elements in the array. Existing keys will be removed. This
function returns TRUE on success, or FALSE on failure

E.g:
<?php Output:
$my_array = array("a" => "Dog", "b" => "Cat", Array
"c" => "Horse"); (
sort($my_array); [0] => Cat
print_r($my_array); [1] => Dog
?> [2] => Horse
)
Array Functions

array_multisort(array1, sortingorder, sorting type,


array2, array3 ) returns a sorted array. You can assign one or
more arrays.

E.g:
<?php
$a1=array(“Dog","Cat");
Output:
$a2=array(“salo",“fido"); Array ( [0] => Cat [1] => Dog )
array_multisort($a1,$a2); Array ( [0] => fido [1] => salo )
print_r($a1);
print_r($a2);
?>
Array Functions

Other Array Functions:

Array array_range(low,high,step) – Populates the array from low value to high


value with the interval of step.
boolean is_array(variable name) – Used to check for an array
Array array_keys(arrayname) – retrieves keys from the array.
Array array_values(array) – retrieves values
int count(arrayname[,mode]) – counts values in an array. Mode – 1 counts
recursively (ie for 2dim array)
sizeof – alias of count.
Array Constants

CASE_LOWER
CASE_UPPER
SORT_ASC
SORT_DESC
SORT_REGULAR
SORT_NUMERIC
SORT_STRING
SORT_LOCALE_STRING
COUNT_NORMAL
COUNT_RECURSIVE

You might also like