Php - Array (Map)

Card Puncher Data Processing

About

In Php, an array is an (ordered|sorted) map (keys/value)

Array can contain others arrays.

Element Structure

(Key|Index)

The key can either be an integer or a string (in the same array - PHP does not distinguish between indexed and associative arrays. ).

While automatically indexing occurs, php will start with the integer 0 and add an increment of 1.

'bar' is a string, while bar is an undefined constant. PHP automatically converts a bar string (an unquoted string which does not correspond to any known symbol) into a string which contains the bar string.

Beware that for other data type, the key will be casted Ie a float of 1.5 will be casted to 1).

Value

The value can be of any type.

Because the value of an array can be anything, it can also be another array. This enables the creation of recursive and multi-dimensional arrays.

// Create a new multi-dimensional array
$juices["apple"]["green"] = "good"; 

Length

sizeof($array)

Offset

offset is not a property but is used by function such as array_splice

To retrieve the offset from a key, search the array of key

$offset = array_search($key, array_keys($myArray), true);

Management

Initialization

If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten.

Empty

// Before 5.4
$myArray = array();

// As of PHP 5.4
$myArray = []; -- empty array, inside the square brackets, you have an expression. $arr[somefunc($bar)] will work

Non Empty

$array = [
    "key" => "value",
    "foo" => "bar",
    "bar" => "foo",
];
//or
$array = array (
    "key" => "value",
    "foo" => "bar",
    "bar" => "foo",
);

Add / Append

Array assignment always involves value copying. (ie not by reference).

At the beginning

array_unshift

  • append one element at the beginning
array_unshift($array, "first");
  • append two elements at the beginning
array_unshift($queue, "0", "1");

At the end

  • Append one element at the end
$input[] = $x; // assign the next index automatically (ie the last one + 1)
  • append two elements at the end
array_push($input, $x, $y);
array_splice($input, count($input), 0, array($x, $y));
// insert into ''$origin'' at index 3, deleting 0, inserting the array ''$inserted''
array_splice( $original, 3, 0, $inserted );
  • array_merge: Only if the arrays contain numeric keys: the value will not overwrite the original value, but will be appended.
$result = array_merge($array1, $array2);

Key / Value Existence (In Operator | Contains )

if array_key_exists('key', $myarray) {
    echo "The 'key' element is in the array";
}
  • in_array — Checks if a value exists in an array
if in_array('value', $myarray) {
    echo "'value' is in the array";
}
  • in_array — Checks if a object exists in an array
if in_array($object, $myarray, TRUE) {
    echo "'object' is in the array";
}

Remove

Remove one element by index

  • unset:
    • preserve the internal pointer position
    • does not rearrange the key sequence
unset($myArray[0]); 
$myArray[0] == null
    • does not preserve the internal pointer position (the pointer is reset to the begining)
    • rearrange the key sequence (from 0,1,2)
array_splice ( $array , 0 , 1 ,  [] );
$myArray[0] == "value of second element"

Remove one element by value

if (($key = array_search($valueToDelete, $array)) !== false) {
    unset($array[$key]);
}

Remove the whole array

unset($myArray); 
  • a value
if (($key = array_search($value, $array)) !== false) {
    unset($array[$key]);
}

Remove at the end (pop)

array_pop

$lastElement = array_pop($array);

Remove at the start (shift)

array_shift

$lastElement = array_shift($array);

(List|Print)

  • To the console
var_dump($array);
print_r($array); // Echo Human readable information
  • In a variable (Retrieve the information in a variable, ie Return the output instead of printing it)
arrayInfo = print_r($array,true); 
  • Json
$json = json_encode($_REQUEST)

Reindex

Reindexed using the array_values() function

Slice

array_slice

array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = FALSE ]] ) : array

Loop

For / While

List

See list

// My
list($var1, $var2, $var3, $var4) = $myArrayOf4Variables;


// From the doc
$info = array('coffee', 'brown', 'caffeine');
list($drink, $color, $power) = $info;
echo "$drink is $color and $power makes it special.\n";

Functional Programming

See PHP - Functional Programming

Count

count($array);

Replace

Scalar value At position

$myArray[1] = "one";
$myArray[3] = "three";

Array by Array (splice)

array_splice

Compare / Diff / Equality

It is possible to compare arrays with the array_diff() function and with array operators.

Sorting

Arrays are ordered. The order can be changed using various sorting functions.

<?php
sort($files);
print_r($files);
?>

Copy

Array assignment always involves value copying. Use the reference operator to copy an array by reference.

$a =& $b; -- =& is the reference operator

a and b point to the same variable space.

Join (to String)

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone

Sort

Sort by value

Ordinal Data - Sorting (Problem / Algorithm) an array in php in ascendant

// if the array contains number
usort($myArray, function($a, $b) {
    return $b - $a; // $a - $b descendant
});

// if the value contains array and that you want to sort on a key
usort($myArray, function($a, $b) {
    return $b['key'] - $a['key'];
});

Sort by key

  • ksort - Sort an array by key
  • asort - Sort an array and maintain index association

Merge / Union

array-merge

if the arrays contain numeric keys, the value will not overwrite the original value, but will be appended.

$array1 = array("color" => "red", 2, 4);
$array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4);
$result = array_merge($array1, $array2);

Documentation / Reference





Discover More
Card Puncher Data Processing
PHP - Functional Programming

in Php is based on : array_map trim all values of the array from the character “ output: Result : array_filter Filtering on key (by default, this is value) array_reduce array_walk...
Card Puncher Data Processing
PHP - While

each Loop over an array with a array_shift
Card Puncher Data Processing
Php - Boolean

This page is the boolean data type in Php. Because of this dynamic nature, php has a weak typing. It considers then a lot of different value as true or false and it can get really confusing. This article...
Card Puncher Data Processing
Php - URL

in php in php You parse it in two steps: first the string format of the query part with parse_url then you put the key/argument of the query in an array with parse_str. URL encoded then...
Card Puncher Data Processing
Php - foreach

foreach is a loop structure over an array foreachFor each



Share this page:
Follow us:
Task Runner