You are on page 1of 38

PHP ARRAYS

• PHP array is an ordered map (contains value on the basis of key). It is


used to hold multiple values of similar type in a single variable.
• Advantage of PHP Array
• Less Code: We don't need to define multiple variables.
• Easy to traverse: By the help of single loop, we can traverse all the elements
of an array.
• Sorting: We can sort the elements of array.
• PHP Array Types
There are 3 types of array in PHP.
• Indexed Array
• Associative Array
• Multidimensional Array
PHP Indexed Array
• PHP index is represented by number which starts from 0. We can store
number, string and object in the PHP array. All PHP array elements are assigned
to an index number by default.
• There are two ways to define indexed array:
• 1st way:
$season=array("summer","winter","spring","autumn");  
• 2nd way:
$season[0]="summer";  
$season[1]="winter";  
$season[2]="spring";  
$season[3]="autumn";  
• Example 1
<?php  
$season=array("summer","winter","spring","autumn");  
echo "Season are: $season[0], $season[1], $season[2] and $season[3]"?>  

• Example 2
<?php  
$season[0]="summer";  
$season[1]="winter";  
$season[2]="spring";  
$season[3]="autumn";  
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";  
?>  
Adding Values to the End of an Array
• To insert more values into the end of an existing indexed array, use
the [] syntax:
$family = array("Fred", "Wilma");
$family[] = "Pebbles"; // $family[2] is "Pebbles"
• This construct assumes the array’s indices are numbers and assigns
elements into the next available numeric index, starting from 0.
Assigning a Range of Values

• The range() function creates an array of consecutive integer or


character values between and including the two values you pass to it
as arguments. For example:
• $numbers = range(2, 5); // $numbers = array(2, 3, 4, 5);
• $letters = range('a', 'z'); // $letters holds the alphabet
• $reversedNumbers = range(5, 2); // $reversedNumbers = 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')
PHP Associative Array
• We can associate name with each array elements in PHP using =>
symbol.
• There are two ways to define associative array:
• 1st way:
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"200000
");  
• 2nd way:
$salary["Sonoo"]="350000";  
$salary["John"]="450000";  
$salary["Kartik"]="200000";  
• Example 1
<?php    
$salary=array("Sonoo"=>"350000","John"=>"450000","Kartik"=>"20000");   
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";  
echo "John salary: ".$salary["John"]."<br/>";  
echo "Kartik salary: ".$salary["Kartik"]."<br/>";  
?>
• Example 2
<?php    
$salary["Sonoo"]="350000";    
$salary["John"]="450000";    
$salary["Kartik"]="200000";    
echo "Sonoo salary: ".$salary["Sonoo"]."<br/>";  
echo "John salary: ".$salary["John"]."<br/>";  
echo "Kartik salary: ".$salary["Kartik"]."<br/>";  
?>    
• Attempting to append to an associative array without appropriate
keys is almost always a programmer mistake, but PHP will give the
new elements numeric indices without issuing a warning:

• $person = array('name' => "Fred");


• $person[] = "Wilma"; // $person[0] is now "Wilma"
Traversing PHP Associative Array
• By the help of PHP for each loop, we can easily traverse the elements
of PHP associative array.
<?php    
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"2000
0"); 
foreach($salary as $k => $v) {  
echo "Key: ".$k." Value: ".$v."<br/>";  
}  
?>    
Keys and Values
• The array_keys() function returns an array consisting of only the keys
in the array in internal order:
$arrayOfKeys = array_keys(array);
• Here’s an example:
$person = array('name' => "Fred", 'age' => 35, 'wife' => "Wilma");
$keys = array_keys($person); // $keys is array("name", "age", "wife")
• PHP also provides a (generally less useful) function to retrieve an
array of just the values in an array, array_values():
$arrayOfValues = array_values(array);
PHP Multidimensional Array
• PHP multidimensional array is also known as array of arrays. It allows you
to store tabular data in an array. PHP multidimensional array can be
represented in the form of matrix which is represented by row * column.
$emp = array  
  (  
  array(1,"sonoo",400000),  
  array(2,"john",500000),  
  array(3,"rahul",300000)  
  );  
PHP
Id MultidimensionalName Array Example Salary
Let's see a simple example of PHP multidimensional array to display following tabular data. In this example, we are displaying 3 rows and 3 columns.

1 sonoo 400000

2 john 500000

3 rahul 300000
<?php    
$emp = array  
  (  
  array(1,"sonoo",400000),  
  array(2,"john",500000),  
  array(3,"rahul",300000)  
  );  
  
for ($row = 0; $row < 3; $row++) {  
  for ($col = 0; $col < 3; $col++) {  
    echo $emp[$row][$col]."  ";  
  }  
  echo "<br/>";  
}  
?>    
PHP Array Functions
• PHP provides various array functions to access and manipulate the elements of array.

1) PHP array() function


• PHP array() function creates and returns an array. It allows you to create indexed,
associative and multidimensional arrays.
• Syntax
array array ([ mixed $... ] )  
Example
<?php    
$season=array("summer","winter","spring","autumn");    
echo "Season are: $season[0], $season[1], $season[2] and $season[3]";    
?>    
2) PHP array_change_key_case() function

• PHP array_change_key_case() function changes the case of all key of an array.


• Note: It changes case of key only.
• Syntax
array array_change_key_case ( array $array [, int $case = CASE_LOWER ] )  
• Example
<?php    
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"20000");    
print_r(array_change_key_case($salary,CASE_UPPER));   
?>    
• Example
<?php    
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");    
print_r(array_change_key_case($salary,CASE_LOWER));   
?>    
3) PHP array_chunk() function

• PHP array_chunk() function splits array into chunks. By using array_chunk() method, you can divide array
into many parts.
• Syntax
array array_chunk ( array $array , int $size [, bool $preserve_keys = false ] )  
Parameter Description
array Required. Specifies the array to use
size Required. An integer that specifies the size of each chunk
preserve_key •Optional. Possible values:true - Preserves the keys
•false - Default. Reindexes the chunk numerically

• Example
<?php    
$salary=array("Sonoo"=>"550000","Vimal"=>"250000","Ratan"=>"200000");    
print_r(array_chunk($salary,2));   
?>    
4) PHP count() function
• PHP count() function counts all elements in an array.
• Syntax
int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL 
] )  
• Example
<?php    
$season=array("summer","winter","spring","autumn");    
echo count($season);    
?>    
5) PHP sort() function
• PHP sort() function sorts all the elements in an array.
• Syntax
bool sort ( array &$array [, int $sort_flags = SORT_REGULAR ] )  
• Example
<?php    
$season=array("summer","winter","spring","autumn");    
sort($season);  
foreach( $season as $s )    
{    
  echo "$s<br />";    
}    
?>    
6) PHP array_reverse() function
• PHP array_reverse() function returns an array containing elements in reversed order.
• Syntax
array array_reverse ( array $array [, bool $preserve_keys = false ] )  
• Example
<?php    
$season=array("summer","winter","spring","autumn");    
$reverseseason=array_reverse($season);  
foreach( $reverseseason as $s )    
{    
  echo "$s<br />";    
}    
?>    
7) PHP array_search() function
• PHP array_search() function searches the specified value in an array. It
returns key if search is successful.
• Syntax
mixed array_search ( mixed $needle , array $haystack [, bool $strict = fal
se ] )  
• Example
<?php    
$season=array("summer","winter","spring","autumn");    
$key=array_search("spring",$season);  
echo $key;    
?>    
8) PHP array_intersect() function

• PHP array_intersect() function returns the intersection of two array. In other words, it returns the
matching elements of two array.
• Syntax
array array_intersect ( array $array1 , array $array2 [, array $... ] )  
• Example
<?php    
$name1=array("sonoo","john","vivek","smith");    
$name2=array("umesh","sonoo","kartik","smith");    
$name3=array_intersect($name1,$name2);  
foreach( $name3 as $n )    
{    
  echo "$n<br />";    
}    
?>    
Padding an Array
• To create an array with values initialized to the same content, use
array_pad().
• The first argument to array_pad() is the array, the second argument is
the minimum number of elements you want the array to have, and
the third argument is the value to give any elements that are created.
• The array_pad() function returns a new padded array, leaving its
argument (source) array alone.
• Example
$scores = array(5, 10);
$padded = array_pad($scores, 5, 0); // $padded is now array(5, 10, 0, 0, 0)
• Notice how the new values are appended to the end of the array.
• If you want the new values added to the start of the array, use a negative
second argument:
$padded = array_pad($scores, −5, 0); // $padded is now array(0, 0, 0, 5,
10);
• If you pad an associative array, existing keys will be preserved. New
elements will have numeric keys starting at 0.
Slicing an Array
• To extract only a subset of the array, use the array_slice() function:
$subset = array_slice(array, offset, length);
• The array_slice() function returns a new array consisting of a consecutive series of values from the original
array.
• The offset parameter identifies the initial element to copy (0 represents the first element in the array), and
the length parameter identifies the number of values to copy.
• The new array has consecutive numeric keys starting at 0.
• For example:
$people = array("Tom", "Dick", "Harriet", "Brenda", "Jo");
$middle = array_slice($people, 2, 2); // $middle is array("Harriet", "Brenda")
• It is generally only meaningful to use array_slice() on indexed arrays (i.e., those with consecutive integer
indices starting at 0):
• // this use of array_slice() makes no sense
$person = array('name' => "Fred", 'age' => 35, 'wife' => "Betty");
$subset = array_slice($person, 1, 2); // $subset is array(0 => 35, 1 => "Betty")
• Checking Whether an Element Exists
To see if an element exists in the array, use the array_key_exists() function:
if (array_key_exists(key, array)) { ... }
• The function returns a Boolean value that indicates whether the first argument is a valid key in the
array given as the second argument.
• It’s not sufficient to simply say:
if ($person['name']) { ... } // this can be misleading
• Even if there is an element in the array with the key name, its corresponding value might be false (i.e.,
0, NULL, or the empty string). Instead, use array_key_exists(), as follows:

$person['age'] = 0; // unborn?
if ($person['age']) {
echo "true!\n";
}
if (array_key_exists('age', $person)) {
echo "exists!\n";
}
Searching for Values
• The in_array() function returns true or false, depending on whether the first
argumentis an element in the array given as the second argument:
if (in_array(to_find, array [, strict])) { ... }
• If the optional third argument is true, the types of to_find and the value in the
array must match. The default is to not check the data types.
• Here’s a simple example:
$addresses = array("spam@cyberpromo.net", "abuse@example.com",
"root@example.com");
$gotSpam = in_array("spam@cyberpromo.net", $addresses); // $gotSpam is true
$gotMilk = in_array("milk@tucows.com", $addresses); // $gotMilk is false
• PHP automatically indexes the values in arrays, so in_array() is generally much
faster than a loop checking every value in the array to find the one you want.
• A variation on in_array() is the array_search() function. While
in_array() returns true if the value is found, array_search() returns the
key of the element, if found:
$person = array('name' => "Fred", 'age' => 35, 'wife' => "Wilma");
$k = array_search("Wilma", $person);
echo("Fred's {$k} is Wilma\n");
Fred's wife is Wilma
• The array_search() function also takes the optional third strict
argument, which requires that the types of the value being searched
for and the value in the array match.
Sorting One Array at a Time
• Sort array by values, then reassign indices starting with 0
• sort() (Ascending)
• rsort() (Descending)
• usort() (User-Defined Order)
• Sort array by values
• asort() (Ascending)
• arsort() (Descending)
• uasort() (User-Defined Order)
• Sort array by keys
• ksort() (Ascending)
• krsort() (Descending)
• uksort() (User-Defined Order)
Examples
• Example 1
$names = array("Cath", "Angela", "Brad", "Mira");
sort($names); // $names is now "Angela", "Brad", "Cath", "Mira“

• Example 2
$logins = array(
'njt' => 415,
'kt' => 492,
'rl' => 652,
'jht' => 441,
'jj' => 441,
'wt' => 402,
'hut' => 309,
);
arsort($logins);
Sorting Multiple Arrays at Once
• The array_multisort() function sorts multiple indexed arrays at once:
array_multisort(array1 [, array2, ... ]);
• Pass it a series of arrays and sorting orders (identified by the SORT_ASC or SORT_DESC
constants), and it reorders the elements of all the arrays, assigning new indices. It is similar to a
join operation on a relational database.
• Imagine that you have a lot of people, and several pieces of data on each person:
$names = array("Tom", "Dick", "Harriet", "Brenda", "Joe");
$ages = array(25, 35, 29, 35, 35);
$zips = array(80522, 02140, 90210, 64141, 80522);

• Here’s how to sort the records first ascending by age, then descending by zip code:
array_multisort($ages, SORT_ASC, $zips, SORT_DESC, $names, SORT_ASC);
Reversing Arrays
• The array_reverse() function reverses the internal order of elements in an array:
$reversed = array_reverse(array);
• Numeric keys are renumbered starting at 0, while string indices are unaffected.
In general,it’s better to use the reverse-order sorting functions instead of
sorting and then reversing the order of an array.
• The array_flip() function returns an array that reverses the order of each
original element’s key-value pair:
$flipped = array_flip(array);
• That is, for each element of the array whose value is a valid key, the element’s
value becomes its key and the element’s key becomes its value.
• For example, if you have an array mapping usernames to home
directories, you can use array_flip() to create an array mapping home
directories to usernames:
$u2h = array(
'gnat' => "/home/staff/nathan",
'frank' => "/home/action/frank",
'petermac' => "/home/staff/petermac",
'ktatroe' => "/home/staff/kevin"
);
$h2u = array_flip($u2h);
$user = $h2u["/home/staff/kevin"]; // $user is now 'ktatroe'
Randomizing Order
• To traverse the elements in an array in random order, use the shuffle() function.
• It replaces all existing keys—string or numeric—with consecutive integers starting at 0.
• Here’s how to randomize the order of the days of the week:
$weekdays = array("Monday", "Tuesday", "Wednesday", "Thursday", "Friday");
shuffle($weekdays);
print_r($days);
Array(
[0] => Tuesday
[1] => Thursday
[2] => Monday
[3] => Friday
[4] => Wednesday
)
• Obviously, the order after your shuffle() may not be the same as the sample output here due to the
random nature of the function.
Calculating the Sum of an Array
• The array_sum() function adds up the values in an indexed or
associative array:
$sum = array_sum(array);
• For example:
$scores = array(98, 76, 56, 80);
$total = array_sum($scores); // $total = 310
Merging Two Arrays
• The array_merge() function intelligently merges two or more arrays:
$merged = array_merge(array1, array2 [, array ... ])
• If a numeric key from an earlier array is repeated, the value from the later array is assigned a
new numeric key:
$first = array("hello", "world"); // 0 => "hello", 1 => "world"
$second = array("exit", "here"); // 0 => "exit", 1 => "here"
$merged = array_merge($first, $second);
// $merged = array("hello", "world", "exit", "here")
• If a string key from an earlier array is repeated, the earlier value is replaced by the later
value:
$first = array('bill' => "clinton", 'tony' => "danza");
$second = array('bill' => "gates", 'adam' => "west");
$merged = array_merge($first, $second);
• // $merged = array('bill' => "gates", 'tony' => "danza", 'adam' => "west")
Calculating the Difference Between Two Arrays
• Another common function to perform on a set of arrays is to get the difference; that is, the values in one
array that are not present in another array.
• The array_diff() function calculates this, returning an array with values from the first array that are not
present in the second.
• The array_diff() function identifies values from one array that are not present in others:
$diff = array_diff(array1, array2 [, array ... ]);
• For example:
$a1 = array("bill", "claire", "ella", "simon", "judy");
$a2 = array("jack", "claire", "toni");
$a3 = array("ella", "simon", "garfunkel");
// find values of $a1 not in $a2 or $a3
$difference = array_diff($a1, $a2, $a3);
print_r($difference);
Array(
[0] => "bill",
[4] => "judy"
);
• Values are compared using the strict comparison operator ===, so 1 and "1" are considered different.
Filtering Elements from an Array
• To identify a subset of an array based on its values, use the array_filter() function:
$filtered = array_filter(array, callback);
• Each value of array is passed to the function named in callback.
• The returned array contains only those elements of the original array for which the
function returns a true value. For example:
$callback = function isOdd ($element)
{
return $element % 2;
};
$numbers = array(9, 23, 24, 27);
$odds = array_filter($numbers, $callback);
// $odds is array(0 => 9, 1 => 23, 3 => 27)
• As you can see, the keys are preserved. This function is most useful with associative
arrays.
Remove duplicate values from an array
• array_unique() Function
Syntax
array_unique(array, sorttype)
• sorttype values
• SORT_STRING - Default. Compare items as strings
• SORT_REGULAR - Compare items normally (don't change types)
• SORT_NUMERIC - Compare items numerically
• SORT_LOCALE_STRING - Compare items as strings, based on current locale

<?php
$a=array("a"=>"red","b"=>"green","c"=>"red");
print_r(array_unique($a));
?>
Output : Array ( [a] => red [b] => green )

You might also like