Sie sind auf Seite 1von 40

PHP Arrays

What is an Array?
-An array can store one or more values
in a single variable name.

-Each element in the array is assigned

its own ID so that it can be easily
-$array[key] = value;
3 Kinds of Arrays

1) Numeric Array
2) Associative Array
3) Multidimensional Array
Numeric Array

- A numeric array stores each

element with a numeric ID key.

- 3 ways to write a numeric array.



$names = array("Peter","Quagmire","Joe");

$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";
The ID can be used in a script
$names[0] = "Peter";
$names[1] = "Quagmire";
$names[2] = "Joe";

echo $names[1] . " and " . $names[2] .

" are ". $names[0] . "'s neighbors";

Quagmire and Joe are Peter's neighbors

Associative Arrays
• An Associative array also is a type of array by which you can
assign an arbitrary key to every value.
• In an associative array, each key is associated with a value.
• With associative arrays we can use the values as keys and
assign values to them.
• In an associative array, the keys are not necessarily numeric,
and even when they are numeric, not necessarily in any
• Syntax of Associative Array
• There are two ways for defining the associative array in PHP.
Which are as follows:
Using an array to assign an age to a person.

$ages = array(”Brent"=>42, ”Andrew"=>25, "Joshua”=>16);

$ages[’Brent'] = ”42";
$ages[’Andrew'] = ”25";
$ages['Joshua'] = ”16";
The Id can be used in a script
$ages[‘Brent’] = ”42";
$ages[‘Andrew’] = ”25";
$ages[‘Joshua’] = ”16";

echo Brent is " . $ages[‘Brent’] . " years old.";


-“Brent is 42 years old.”

Multidimensional Arrays
• A Multidimensional array is also known as a two-
dimensional array.
• A Multidimensional array is an array of arrays i.e.
each element in the main array can also be an
• And each element in the sub-array can be an
array, and so on.
• A multidimensional array is an array of arrays,
which means that the array can contain arrays
within itself.
• If an array element value is another array then
this is a multidimensional array.
• Syntax of Multidimensional Array

• $arrayname = array ($array1, $array2,

$array3) ;
$families = array
"Megan" ),
"Quagmire"=>array ( "Glenn" ),
[Griffin] => Array
echo "Is " . $families['Griffin'][2] .
[0] => Peter " a part of the Griffin family?";
[1] => Lois
[2] => Megan
[Quagmire] => Array
( Is Megan a part of the
[0] => Glenn
Griffin family?
[Brown] => Array
[0] => Cleveland
[1] => Loretta
[2] => Junior
In depth of Arrays
• To construct an empty array, pass no arguments
to array();
– Ex: $addr=array();
• You can specify an initial key with => and then a
list of values.
• The values are inserted into the array starting
with that key, with subsequent values having
sequential keys:
– $days=array(1=>’Monday’, ‘Tuesday',' Wednesday’);
• If the initial index is a non-numeric string,
subsequent indexes are integers beginning at 0.
• $colors=array('Friday'=>'Blue','Pink','Green');
// same as
• $colors=array('Friday‘ => 'Blue', 0 => 'Pink',
foreach($colors as $w) //for iterating
echo $w."<br>";
Adding values to the End of an
• To insert more values into the end of an
existing indexed array, use the [] syntax:
– $subjects=array(‘OSS’, ‘Android’);
– $subjects[]= ‘SOA’; //$subjects[2] is ‘SOA’
• Attempting to append to an associative array is
almost always a programmer mistake, but PHP
will give the new elements numeric indices
without issuing a warning:
– $person = array(‘name => ‘aswin’);
– $person[] = ‘kavin’; //$person[0] is now ‘kavin’
Assigning a Range of values
• The range() function creates an array of
consecutive integer or character values
between the two values you pass to it as
– $nos = range(2,5); //$nos=array(2,3,4,5);
– $letters=range(‘a’, ‘z’); //$letters holds the alphapet
– $r_nos=range(5,2); //$r_nos=array(5,4,3,2);
• Only the first letter of a string argument is
used to build the range:
– Range(‘aaa’, ‘zzz’); //same as range(‘a’,’z’);
Getting the size of an Array
• The count() and sizeof() functions are
identical in use and effect.
• Both returns the no. of elements in the array.
• $items=array(‘pen’, ‘pencil’, ‘eraser’);
• $size=count($items); //$size is 3
Padding an Array
• To create an array with values initialized to
the same content, use array_pad().
• The 1st argument to array_pad() is the array.
• The 2nd argument is the minimum no. of
elements you want the array to have.
• The 3rd argument is the value to give any
elements that are created.
• This function returns a new padded array.
Padding - Example
– $scores = array(90,50);
– $pad_score=array_pad($scores,5,0);
//$pad_score is now array(90,50,0,0,0)
• If you want the new values added to the start
of the array, use a negative 2nd argument.
– $pad_arr = array_pad($scores,-5,0);
• If you pad an associative array, existing keys
will be preserved. New elements will have
numeric keys starting at 0.
Extracting multiple values
• To copy all of an array’s values into variables,
use the list() construct:
– List($variable, ….) = $array;
• The array’s values are copied into the listed
variables in the array’s internal order.
• By default that’s the order in which they were
– $person=array(‘yasmin’, 23, ‘mca’);
– List($name, $age, $degree) = $person;
Slicing an array
• To extract only a subset of the array, use the
array_slice() function:
– $subset = array_slice(array, offset, length);
• It returns a new array consisting of a
consecutive series of values from the original
• The offset parameter identifies the initial
element to copy.
• The length parameter identifies the no. of
values to copy.
Slicing Example
• $colors = array(‘red’, ‘blue’,’yellow’, ‘pink’);
• $middle = array_slice($colors, 2,2);
• It is generally only meaningful to use
array_slice() on indexed arrays.
• Meaningless Example:
– $person=array(name=>‘yasmin’,age=>
23,degree=> ‘mca’);
– $middle = array_slice($person, 1,2);
Slice Example
• Combine array_slice() with list() to extract
only some values to variables.

• $order =
• List($second, $third) = array_slice($order,1,2);
• What is the value of $second and $third?
Splitting an array into chunks
• To divide an array into smaller, evenly sized
arrays, use the array_chunk() function.
– $chunks=array_chunk(array, size [, preserve_keys]);
• This function returns an array of the smaller
• The 3rd argument preserve_keys, is a Boolean
value that determines whether the elements of
the new arrays have the same keys as in the
original (useful for associative arrays).
• The default is to assign new keys (i.e. false).

$nums = range(1, 7);

$rows = array_chunk($nums,3);
Ex: arrchunk.php
Array{ }
[0] => Array [2] => Array
{ {
[0] => 1 [0] => 7
[1] => 2 }
[2] => 3 }
[1] => Array
[0] => 4
[1] => 5
[2] => 6
Keys and Values
• The array_keys() function returns an array
consisting of only the keys in the array in
internal order.
– $keys = array_keys(array);
• $person = array(‘name’=>’sathish’, ‘age’=>50,
• $arrkeys=array_keys($person); // It returns
the new array with the keys of person’s array.
• i.e., arrkeys is array(‘name’,’age’,’degree’);
Keys & values
• PHP also provides a function to retrieve an
array of just the values in an array.
• $arr_values = array_values(array);
• Ex: $values=array_values($person);
• But it is less generally useful or used.
Checking whether an element
exists with key value
• Array_key_exists() function is used.
• Syntax:
– Array_key_exists(key,array);
• Ex:
– If (array_key_exists(‘age’,$person))
{ }
Searching for values
• In_array() – returns true / false, depending on
whether the 1st argument is an element in the
array given to the 2nd argument.
• Ex:
– $ext=array(‘jpg’,’jpeg’,’gif’,’png’);
– $ans=in_array(‘docx’,$ext); // Returns ?
– $ans=in_array(‘jpg’,$ext); // Returns ?
• Array_search() – returns the key of the found
Calculating the sum of an Array
• Array_sum() – adds up the values in an
indexed or associative array.
• Syntax:
• $var=array_sum(array);
• Ex: $marks=array(50,90,40);
• $tot=array_sum($marks); //$tot=130
Merging & difference
• Array_merge()
• $newarray=array_merge($array1, $array2..);

• Array_diff() – it uses === operator & it

preserves keys.
• $newarray=array_diff($array1,$array2,$array
• Ex:$diff=array_diff($a1,$a2,$a3);
• //find values of $a1 in $a2 or $a3
Array Traversal
• The simplest and the most widely used
method for this is the foreach operator which
loops through the whole array and works
individually with each key/item couple.
• If a more complex way of traversing the array
is needed, the following functions operate
using the internal array pointer.
Traversal functions
• Reset – sets the internal ptr to the first
element and returns the first element.
• Prev – sets the internal ptr to the previous
element and returns it.
• Current – returns the current element; does
not change the internal ptr.
• Next – sets the internal ptr to the next
element and returns it.
• Each – returns the current element; then sets
the internal ptr to the next element.
• End – sets the internal ptr to the element and
returns the last element.
echo $i.”\n”;