Monday 2 February 2015

PHP Array

PHP Array

Use PHP Array as a key & value map

# PHP array contains elements of key/value pair
$a = array('text' => 'string', 10 => 4, 'absent' => TRUE);

echo $a['text'];               # 'string'
echo $a[10];                   # 4
echo $a['absent'];             # 1

echo "$a[text]";               # If the variable is inside double quote "", text does NOT need to be quoted
Accessing PHP Array using index
$a = array('text' => 'string');
echo $a['text'];               # 'string'

define('text', 'constant');
echo $a[text];                 # A common mistake: not the same as $a['text']
                               # text here refer to the global constant (text)
PHP array key
  • Can either be a string or an integer
  • Other numeric type will truncate to an integer
Removing (unset) PHP array elements
unset($a[4]);         # Delete an element of an array
unset($a);            # Delete $a

Use PHP Array as a 1-dimensional array

$a1 = array(2, 1, 0);          # Without a key, key value starts from 0 and increment by 1 each time
                               # array(3) { [0]=> int(2) [1]=> int(1) [2]=> int(0) }
                               # An array of length 3 with key 0, 1 & 2
Append an element to the end of a PHP array
$a1[] = 4;                     # Append an element: array(0=>2, 1=>1, 2=>0, 3=>4)
Create an empty PHP array
$a1 = array();                 # Empty array
Start a PHP array with a specific key value
$months = array(1=>'Jan', 'Feb', 'Mar', 'Apr'); # Key starts from 1

$a2[3] = 9;                    # array(1) { [3]=> int(9) }
Create a PHP array with a range of value
$a = range(0, 5);              # array(0, 1, 2, 3, 4, 5);
$a = range('a', 'z');

Multi-dimensional PHP Array

$a = array("item" => array("text" => "string", 10 => 4, "absent" => TRUE) , 'flag' => TRUE);

echo $a['item']['text'];                # 'string'
echo $a['item'][10];                    # 4
echo $a['item']['absent'];              # 1

PHP Array indexing

When a key is missing ($a[] = 'text'; ), PHP uses the next available integer index
  • Find the maximum integer index (n) used in the array
  • Use n+1 as the next index
    $a = array(1 => '0', 3 => 'a', 'b', 'c', 'flag' => 'b', 20 => 'y', 'z');
    echo $a[3];           # 'a'
    echo $a[4];           # 'b'
    echo $a[5];           # 'c'
    echo $a[21];          # 'z'
    
    $a[] = 'd';           # Same as $a[22] = 'd' which 22 is the next index value for $a
    $a['option'] = 'e';

PHP Array Key & Value Functions

Return all keys in a PHP array
$a = array(3 => 'a', 'b', 'c');
$k = array_keys($a);
Re-index the array with key starts from 0
$a2 = array_values($a);

Check the presence of a key or a value in a PHP array

Find if a key exists in a PHP array
$b = array_key_exists('key_name', $a);   # TRUE if key exists
$b = isset($a['key_name']);              # TRUE if key exists and the value is not NULL
Find if a specific element exists in a PHP array
$a = array('x', 'y', 'z');
$b = in_array('x', $a);                    # TRUE: 'x' is in $a
Find the key by the PHP array element value
$k = array_search('x', $a);                # Return the key for value 'x'

PHP Array Copy, Replace, Insert & Delete

PHP array assignment (PHP array assignment is copy by value)
$a = array('a', 'b', 'c');
$a2 = $a;
  • A duplicate copy of the array (copy by value) is made
  • Change in one array have no impact on other
    $a = array("original");
    $b = $a;
    $a[0] = "new";   // $b[0] will remain as "original"
To copy PHP array by reference
$a3 = &$a;           # A variable alias. Changes impact both $a and $a3
Return a sub-set of a PHP array
$r = array_slice($a, 1, 2);                # Return an array starting at index 1 with max of 2 elements
                                           # array(2) { [0]=> string(1) "b" [1]=> string(1) "c" }
Merge PHP array elements into sub-array of size 2
$r = array_chunk($a, 2);                   # Merge array elements into sub-array elements of size 2
                                           # array(2) { [0]=> array(2) { [0]=> string(1) "a" [1]=> string(1) "b"}
                                           #            [1]=> array(1) { [0]=> string(1) "c" } }
                                           #
Remove PHP array elements
$r = array_splice($a, 2, 3);               # Remove max of 3 elements starting at index 2 from $a (in-place)
                                           # The removed elements are stored in $r
                                           # $a: array(2) { [0]=> string(1) "a" [1]=> string(1) "b"}
                                           # $r: array(1) { [0]=> string(1) "c"}

$r = array_splice($a, 2);                  # Remove elements of $a starting at index 2 to the end

$r = array_splice($a, 1, 2, array(4, 5));  # Remove and then insert an array
Pad a PHP array
$r = array_pad($a, 5, 0);                  # Pad the array with 0 to a max of 5 elements

PHP Array Function

Assign array's element to different variables
$a = array(1, 2, 3);
list($v1, $v2, $v3, $v4) = $a;   # Assign $v1=$a[0]; $v2=$a[1]; $v3=$a[2]; $v4=NULL;
Un-pack the returned function's array result to a list of PHP variables
list($v1, $v2, $v3, $v4) = some_func();  # some_func() can return an array like return array(1, 3);
Merge 2 PHP arrays
$r = array_merge($a1, $a2); # Merge 2 array with $a1 elements come first
                            # If an element in $a2 has the same key as $a1, $a2 value will be used
PHP Array difference
$a1 = array(1,2);
$a2 = array(2,3);
$r = array_diff($a1, $a2);       # Return an array containing the difference
                                 # array(1) { [0]=> int(1) }
Count the number of elements in a PHP array
$t = count($a);             # Number of count
Sum all the elements of a PHP array
$total = array_sum($a);     # Sum of array elements
print_r($a1);               # Print the array
Reverse, Flip or Shuffle PHP array elements
$r = array_reverse($a);     # Reverse an array

$r = array_flip($a);        # Flip the key with value

shuffle($a);                # Randomized the order of the elements
Use function call back to filter out PHP array elements
function is_even ($v) {
  if (($v%2)==0) {
   return TRUE;
  }
  return FALSE;
}

$a = array(1, 6, 2, 4);
$r = array_filter($a, 'is_even');   # Create another array from $a that has even number only
Create variables from array (or vice versa)
$a = array("v1" => 1, "v2" => 2);          # Create variables from array
extract($a, EXTR_PREFIX_ALL, "value");     # Same as $value_v1=1; $value_v2 = 2;

$v1 = 1;
$v2 = 2;                                   # Opposite of extract
$a = compact('v1', 'v2');                  # array(2) { ["v1"]=> int(1) ["v2"]=> int(2) }

PHP array operation

PHP Array OperationDescription
$a1 + $a2Union
$a1 == $a2Equal if both array have the same key/value pairs
$a1 === $a2Equal if both have the same key/value pairs in the same order and of types
!= <>Not ==
$a !== $bNot ===

PHP Array Iteration

Iterate through a PHP array
$months = array(1=>'Jan', 'Feb', 'Mar', 'Apr');
foreach ($months as $month) {
   echo "$month";
}
Iterate through a PHP array with key & value pair
foreach ($months as $key => $month) {
   echo "$key $month";
}
Iterate through a PHP array with key & value pair by reference
foreach ($months as &$month) {           # Pass by reference
   $month = strtoupper($month);          # so in-place assignment is possible
}
 without the reference, making change to "$month" will have no impact on the $months array

PHP iterate function

# Reset the iterator to the beginning
reset($a);

# Iterate each key/value in the array
while (list($key, $value) = each($a)) {
      echo $key, $value;
}
PHP Array Iteration FunctionDescription
current( )Current iterator element
reset( )Move back to first element
next( )Move to next element and return it
prev( )Move back and return it
end( )Move to last element and return it
each( )return current key/value as an array and move to next element
key( )key of current element

PHP array_walk: Calling a function in visiting every element of a PHP array

function visit($value, $key) {
  ...
}

function visit2($value, $key, $p1) {
  ...
}

$a = array(1, 2, 3);
array_walk($a, 'visit');
array_walk($a, 'visit2', 'some parameter');

PHP Array Aggregate features

function sum ($total, $value) {
  $total += $value;
  return $total;
}

$a = array(1, 2, 3);
$sum = array_reduce($a, 'sum');    # 6
$sum = array_reduce($a, 'sum', 4); # 10: Start $total with 4

PHP Array Sorting Functions

PHP Array FunctionSorts byMaintain key/value associationSorting order
array_multisort()valueNot on numeric keyfirst array
asort()valueyesASC
arsort()valueyesDESC
krsort()keyyesDESC
ksort()keyyesASC
natcasesort()valueyesNatural & case insensitive
natsort()valueyesNatural
rsort()valueno (key restart from 0)DESC
shuffle()valueno (key restart from 0)Random
sort()valueno (key restart from 0)ASC
uasort()valueyesUser defined
uksort()keyyesUser defined
usort()valueno (key restart from 0)User defined
sort($a);
PHP user define comparator
function custom_sort($a, $b) {
   if ($a == $b) {
     return 0;
   }
   return (($a < $b) ? -1 : 1);
}

$a = array (1, 4, 4, 2, 7);
uasort($a, 'custom_sort');
Sort array that contain value with both numeric and string (like 'time3', 'time10')
natsort($a);
natcasesort($a);
Sort by $a1, then $a2 and last $a3
array_multisort($a1, SORT_ASC, $a2, SORT_DESC, $a3, SORT_DESC);

PHP Array Functions (Quick Reference)

FunctionsDescription
array_change_key_caseChange the case of the keys
array_chunkSplit an array into chunks
array_combineCreate an array using one array as keys and another for values
array_count_valuesCount the number of occurrence for unique key
array_diff_assocFind the difference. Comparing key/value
array_diff_keyFind the difference. Only comparing key
array_diff_uassocFind the difference with user defined comparator on indexes
array_diff_ukeyFind the difference with user defined comparator on keys
array_diffDifference on an array
array_fill_keysFill an array with value/key
array_fillFill an array with values
array_filterFilters elements of an array with a callback function
array_flipFlip key/value
array_intersect_assocIntersection of arrays with index check
array_intersect_keyIntersection of arrays using keys for comparison
array_intersect_uassocIntersection of arrays with index check with a callback function
array_intersect_ukeyIntersection of arrays using a callback function on the keys
array_intersectIntersection of arrays
array_key_existsKey exists in an array
array_keysReturn an array of all keys
array_mapCall the callback for all elements in an array
array_merge_recursiveMerge two or more arrays recursively
array_mergeMerge one or more arrays
array_multisortSort multiple or multi-dimensional arrays
array_padPad array
array_popPop the element from an array
array_productProduct of values in an array
array_pushPush an array
array_randPick an element randomly
array_reduceAggregate the array to a single value using a callback function
array_replace_recursiveReplaces elements of first array by another array recursively
array_replaceReplaces elements of first array by another array
array_reverseReverse an array
array_searchSearch for a given value and return the key
array_shiftShift an element off from the beginning
array_sliceSlice an array
array_spliceSlice an array and replace it with other elements
array_sumSum of an array
array_udiff_assocThe difference of arrays with index check & compares value with a callback function
array_udiff_uassocThe difference of arrays with index check, compares key/value with a callback function
array_udiffThe difference of arrays comparing value with a callback function
array_uintersect_assocIntersection of arrays with index check, compares value with a callback function
array_uintersect_uassocThe intersection of arrays with index check, compares key/values with a callback functions
array_uintersectThe intersection of arrays, compares value with a callback function
array_uniqueRemoves duplicate values
array_unshiftPrepend elements to the beginning of an array
array_valuesValues of an array
array_walk_recursiveCall a user function for each element of an array recursively
array_walkCall a user function for each element of an array
arrayCreate an array
compactCreate array with variables/values
countCount elements in an array
extractImport variables from an array
in_arrayValue exists in an array
listAssign variables from an array
rangeAn array containing a range of values
shuffleShuffle an array
sizeofCount of an array

0 comments:

Post a Comment