In my previous article Arrays in PHP, I had discussed about creating and printing arrays. In this article, I would discuss some more things we can do with Arrays. But before that, let's check one complex array below :
<?php
$arr = array (
'name' =>
array('first_name' => 'Robin',
'middle_name' => '',
'surname' => 'Smith'),
'dob' => '14/Jan/1980',
'lucky_nos' => array(
'numerology_based' => 1,
'chinese_astro_based' => 2 ),
'grade_years' => array(
'2001' => 'A+',
'2002' => 'B+',
'2003' => 'C+' ),
'ph_nos' => array(
'2202-3256',
'father' => '4545-2256')
);
?>
In the above multi-dimensional associative array, a student info has been stored under various "key" => "value" pair combinations.
Now, if we want to add some more information to it, we would do it the following way.
<?php
$arr['favourite_color'] = array('blue','pink') ;
?>
So, a new key 'favourite_color' will be created holding an array of 'blue' and 'pink'. But, if we do it the following way ::
<?php
$arr[] = array( 'favourite_color' => array('blue','pink') ) ;
?>
next available index 0 (Zero) will be created. So all the indices within the array will be 'name', 'dob', 'lucky_nos', 'grade_years', 'ph_nos' and 0 (zero). It is same as writing the following statement (in this context)::
<?php
$arr[0] = array( 'favourite_color' => array('blue','pink') );
?>
In case of Associative arrays, the keys would have automatically casts to Integers as shown below :
<?php
$arr = array (
0 => 'Philippe',
'0' => 'John', // String to Integer 0
0.9 => 'Mick', // Float to Integer 0
false => 'Andrew', // 'false' is cast to Integer 0
NULL => 'Rahman' // NULL is cast to ''
);
print_r( $arr );
?>
All the index '0' (as string), '0.9' (as float/double), 'NULL' (as NULL), 'false' (as boolean) will be converted to integer 0. In case of floating point number, the fractional part is totally discarded, hence, for example, '1' will be accepted as key for given keys like '1.23', '1.67' or '1.09'. In our example above, first four keys are evaluated to 0 (zero) and hence $arr[0] will have the last value 'Andrew' as every time old value is overwritten. The key 'NULL' is cast to empty string. Check out the output below :
Array
(
[0] => Andrew
[] => Rahman
)
Copying an array to another is very simple. All the 'key'=>'value' combination are preserved while copying to another array.
<?php
// Simple copy
$arr2 = $arr;
?>
However, if we create a reference to that array, any changes to original array would reflect in the reference. Check the example below.
<?php
// Create a reference
$arr3 = & $arr;
?>
Next, we would work on some array operators. Let's start with '+' operator, which unions two array. Check the example below.
<?php
// First array : index 0,1
$arr1 = array( 1, 2 );
// Second array : index 0,1
$arr2 = array( 2, 3 );
// Add them using '+' operator
// $arr1 if first operand
print_r( $arr1 + $arr2 );
// $arr2 is first operand
print_r( $arr2 + $arr1 );
?>
The output will be
Array ( [0] => 0 [1] => 1 )
Array ( [0] => 2 [1] => 3 )
In case of $arr1 + $arr2, as the $arr2 also has index '0' and '1', $arr1's (former array) values will be preserved. Hence the first print_r() print's $arr1's values.
But in case of $arr2 + $arr1, the second print_r() prints just the opposite as first operand $arr2's values are preserved. Check another example ::
<?php
// both the Arrays have indices 0 and 1
$arr1 = ('apple','banana');
$arr2 = ('mango','orange');
// Outputs array(0=>'apple', 1=>'banana')
print_r( $arr1 + $arr2 );
?>
Here the first array - $arr1's index/value pairs will be preserved as the second array also has the same indices.
If both the arrays have different key=>value combinations, the resultant array can have all the key=>value combinations as shown in the example below ::
<?php
// First array : index 0,1
$arr1 = array( 1, 2 );
// Second array : index 2,3
$arr2 = array( 2=>2, 3=>3 );
// Add them using '+' operator
// $arr1 if first operand
print_r( $arr1 + $arr2 );
// $arr2 is first operand
print_r( $arr2 + $arr1 );
?>
Here is the output
Array ( [0] => 1 [1] => 2 [2] => 2 [3] => 3 )
Array ( [2] => 2 [3] => 3 [0] => 1 [1] => 2 )
In the first case, $arr2's index and value combinations are appended to $arr1's same combination whereas in the second case, $arr1's key value pairs are appended to $arr2's same pairs.
Next, we can use operators '==', '<=', '>=' for array comparisons. Keys should match on both the arrays for such comparison. Array with lesser number of values are smaller in case of comparison. If keys are same, then values are checked. Check the example below :
<?php
$arr1 = array ( 1=>1, 2=>2 );
$arr2 = array ( 2=>2, 3=>3 );
// Uncomparable as index don't match
echo $arr1 == $arr2;
$arr1 = array ( 1=>1, 2=>2 );
$arr2 = array ( 1=>2, 2=>4 );
// $arr2 has larger values
echo $arr1 <= $arr2; // Outputs 1
?>
Let's see how to deal with situations where a function returns an array.
<?php
// Define a Function which returns array
function return_array(){ return array(1,2,3,4); }
// As of PHP 5.4, access the 3rd element
$fourth_elem = return_array()[3];
// Otherwise, store it in some
// other variable
$arr = return_array();
// Access Array Items
$fourth_elem = $arr[3];
?>
Objects and other data types can be typecast to array. Check out some examples below :
<?php
class a
{
private $name = 'Robin';
private $age = 15;
public $roll = 1;
protected $ph = 909090;
}
// Create Object of class a
$obj = new a();
// Object to Array
$arr = (array) $obj ;
// Member names will be the
// KEYS in the resultant array
print_r( $arr );
// String to Array
$name = 'Robin' ;
$arr = (array) $name;
print_r( $arr );
?>
While typecasting from Object, the member variables' names become the keys of the resultant array. For private variables, class is prepended to the key, for public variables the key is same as the variable name, for protected variable a '*' is prepended to the key. The characters/strings which are prepended to the key are wrapped by NULL (\0) characters. These NULL characters can be seen if we var_dump() the array.
Check the output of the above code :
Array
(
[aname] => Robin
[aage] => 15
[roll] => 1
[*ph] => 909090
)
Array
(
[0] => Robin
)
Arrays types are very flexible in PHP. We would discuss more on it in later articles.
<?php
$arr = array (
'name' =>
array('first_name' => 'Robin',
'middle_name' => '',
'surname' => 'Smith'),
'dob' => '14/Jan/1980',
'lucky_nos' => array(
'numerology_based' => 1,
'chinese_astro_based' => 2 ),
'grade_years' => array(
'2001' => 'A+',
'2002' => 'B+',
'2003' => 'C+' ),
'ph_nos' => array(
'2202-3256',
'father' => '4545-2256')
);
?>
In the above multi-dimensional associative array, a student info has been stored under various "key" => "value" pair combinations.
Now, if we want to add some more information to it, we would do it the following way.
<?php
$arr['favourite_color'] = array('blue','pink') ;
?>
So, a new key 'favourite_color' will be created holding an array of 'blue' and 'pink'. But, if we do it the following way ::
<?php
$arr[] = array( 'favourite_color' => array('blue','pink') ) ;
?>
next available index 0 (Zero) will be created. So all the indices within the array will be 'name', 'dob', 'lucky_nos', 'grade_years', 'ph_nos' and 0 (zero). It is same as writing the following statement (in this context)::
<?php
$arr[0] = array( 'favourite_color' => array('blue','pink') );
?>
In case of Associative arrays, the keys would have automatically casts to Integers as shown below :
<?php
$arr = array (
0 => 'Philippe',
'0' => 'John', // String to Integer 0
0.9 => 'Mick', // Float to Integer 0
false => 'Andrew', // 'false' is cast to Integer 0
NULL => 'Rahman' // NULL is cast to ''
);
print_r( $arr );
?>
All the index '0' (as string), '0.9' (as float/double), 'NULL' (as NULL), 'false' (as boolean) will be converted to integer 0. In case of floating point number, the fractional part is totally discarded, hence, for example, '1' will be accepted as key for given keys like '1.23', '1.67' or '1.09'. In our example above, first four keys are evaluated to 0 (zero) and hence $arr[0] will have the last value 'Andrew' as every time old value is overwritten. The key 'NULL' is cast to empty string. Check out the output below :
Array
(
[0] => Andrew
[] => Rahman
)
Copying an array to another is very simple. All the 'key'=>'value' combination are preserved while copying to another array.
<?php
// Simple copy
$arr2 = $arr;
?>
However, if we create a reference to that array, any changes to original array would reflect in the reference. Check the example below.
<?php
// Create a reference
$arr3 = & $arr;
?>
Next, we would work on some array operators. Let's start with '+' operator, which unions two array. Check the example below.
<?php
// First array : index 0,1
$arr1 = array( 1, 2 );
// Second array : index 0,1
$arr2 = array( 2, 3 );
// Add them using '+' operator
// $arr1 if first operand
print_r( $arr1 + $arr2 );
// $arr2 is first operand
print_r( $arr2 + $arr1 );
?>
The output will be
Array ( [0] => 0 [1] => 1 )
Array ( [0] => 2 [1] => 3 )
In case of $arr1 + $arr2, as the $arr2 also has index '0' and '1', $arr1's (former array) values will be preserved. Hence the first print_r() print's $arr1's values.
But in case of $arr2 + $arr1, the second print_r() prints just the opposite as first operand $arr2's values are preserved. Check another example ::
<?php
// both the Arrays have indices 0 and 1
$arr1 = ('apple','banana');
$arr2 = ('mango','orange');
// Outputs array(0=>'apple', 1=>'banana')
print_r( $arr1 + $arr2 );
?>
Here the first array - $arr1's index/value pairs will be preserved as the second array also has the same indices.
If both the arrays have different key=>value combinations, the resultant array can have all the key=>value combinations as shown in the example below ::
<?php
// First array : index 0,1
$arr1 = array( 1, 2 );
// Second array : index 2,3
$arr2 = array( 2=>2, 3=>3 );
// Add them using '+' operator
// $arr1 if first operand
print_r( $arr1 + $arr2 );
// $arr2 is first operand
print_r( $arr2 + $arr1 );
?>
Here is the output
Array ( [0] => 1 [1] => 2 [2] => 2 [3] => 3 )
Array ( [2] => 2 [3] => 3 [0] => 1 [1] => 2 )
In the first case, $arr2's index and value combinations are appended to $arr1's same combination whereas in the second case, $arr1's key value pairs are appended to $arr2's same pairs.
Next, we can use operators '==', '<=', '>=' for array comparisons. Keys should match on both the arrays for such comparison. Array with lesser number of values are smaller in case of comparison. If keys are same, then values are checked. Check the example below :
<?php
$arr1 = array ( 1=>1, 2=>2 );
$arr2 = array ( 2=>2, 3=>3 );
// Uncomparable as index don't match
echo $arr1 == $arr2;
$arr1 = array ( 1=>1, 2=>2 );
$arr2 = array ( 1=>2, 2=>4 );
// $arr2 has larger values
echo $arr1 <= $arr2; // Outputs 1
?>
Let's see how to deal with situations where a function returns an array.
<?php
// Define a Function which returns array
function return_array(){ return array(1,2,3,4); }
// As of PHP 5.4, access the 3rd element
$fourth_elem = return_array()[3];
// Otherwise, store it in some
// other variable
$arr = return_array();
// Access Array Items
$fourth_elem = $arr[3];
?>
Objects and other data types can be typecast to array. Check out some examples below :
<?php
class a
{
private $name = 'Robin';
private $age = 15;
public $roll = 1;
protected $ph = 909090;
}
// Create Object of class a
$obj = new a();
// Object to Array
$arr = (array) $obj ;
// Member names will be the
// KEYS in the resultant array
print_r( $arr );
// String to Array
$name = 'Robin' ;
$arr = (array) $name;
print_r( $arr );
?>
While typecasting from Object, the member variables' names become the keys of the resultant array. For private variables, class is prepended to the key, for public variables the key is same as the variable name, for protected variable a '*' is prepended to the key. The characters/strings which are prepended to the key are wrapped by NULL (\0) characters. These NULL characters can be seen if we var_dump() the array.
Check the output of the above code :
Array
(
[aname] => Robin
[aage] => 15
[roll] => 1
[*ph] => 909090
)
Array
(
[0] => Robin
)
Arrays types are very flexible in PHP. We would discuss more on it in later articles.