Php array index data type

Mastering PHP arrays: Array basics

An array is one of the most powerful and flexible data types in PHP.

Arrays are ordered collections of items, called array elements, and are actually an implementation of ordered maps or more precisely hash tables.

Arrays are flexible in defining keys and values. They are capable of storing any value, including other arrays, trees and multidimensional arrays. Every value has its key although it is not defined implicitly by its definition.

Creating arrays

An array can be created using the array() language construct or as of PHP 5.4 short array syntax [] . Array elements can be assigned to variable in multiple ways:

 1php  2  3$array1 = array();  4$array2 = []; // as of PHP 5.4  5  6$array1[] = 11;  7$array1[] = 2;  8$array1[] = 0;  9 10$array3 = array(11, 2, 0); 11 12$array4 = [ 13 'a' => 'A', 14 20 => 'bar', 15 'x' => 'baz', 16 55, 17 '22' => 2015, 18 null => null, 19 '012' => 'Hello', 20 true => 'World', 21 3.14 => 'Phi', 22]; 

Variables $array1 and $array2 have assigned empty array. Variable $array2 has an empty array value assigned by short syntax.

Variable $array1 is filled with values 11 , 2 and 0 afterwards. These values are appended to the empty array using assign operator and square bracket syntax: arrayPhp array index data type = value . Since every member of an array must have a key, a numeric key starting from 0 is assigned to every element automatically.

An array construct enables to fill the array with values at its creation using index => value syntax separated by commas. When an index is omitted, the integer index is automatically generated. The variable $array3 is created using array construct parameters and it’s identical to the $array1 .

Variable $array4 is created using short array syntax and it’s filled with mixed key data types. The last element of the array has a trailing comma. While unusual, it is a valid syntax. It’s a good practice to leave a trailing comma in multiline array definitions.

PHP supports only integer and strings keys. Other data types are cast to these two based on casting rules.

Handling array keys

Array keys are unique values and can be either integers or strings. Data type other then this will be cast to these data types by following casting rules:

Data type Cast to Original value Cast value Notice
String Integer/String «3» / «03» 3 / «03» valid decimal integers will be cast to the integer type, other numbers will not be cast
Float Integer 3.14 3 fractional part will be truncated
Bool Integer true 1 the key true will actually be stored under 1 and the key false under 0
Null String null «» key null will actually be stored under «»
Array/Object illegal type; will produce Warning: Illegal offset type . error

Note that array keys are case-sensitive but type insensitive and elements with same keys are overwritten with a later declaration. Arrays are type insensitive because they are using a special type of hash table called symtable. Integers and numeric strings in a symtable are considered identical and because of this value stored in an array as $array[‘1’] can be also accessed as $array[1] .

Typecasting and overwriting example:

1php 2 3$array = [ 4 '0' => 'apple', 5 0 => 'banana', 6 false => 'lemon', 7 0.999 => 'orange', 8 '1' => 'melon' 9]; 

Finally this array will contain only element with key 0 and value ‘orange’ and element with key 1 and value ‘melon’ .

Arrays are limited by implementation of hash tables and its maximum number of elements, and the memory_limit. The maximum number of elements depends on OS architecture. Enumerative arrays are also limited by the maximum size of an integer.

Let’s consider this example:

1php 2 3// PHP_INT_MAX = 2^63-1 for tested OS 4 for ($index = -2; $index  2; ++$index)  5 $array[PHP_INT_MAX + $index] = $index; 6> 

An array from the example above will look like this:

1Array 2( 3 [9223372036854775805] => -2 4 [9223372036854775806] => -1 5 [9223372036854775807] => 0 6 [-9223372036854775808] => 2 7) 

After the PHP_INT_MAX limit was exceeded, overflow happened and a value with a key -9223372036854775808 was overwritten with the later declaration of the value.

Enumerative vs. Associative arrays

Arrays can roughly be divided into two categories:

  • Enumerative: indexed using only numerical indexes
  • Associative: indexed using arbitrary indexes

PHP arrays can contain integer and string keys at the same time as PHP does not distinguish between indexed and associative arrays. This enables to create an enumerative array, insert associative element to it and PHP will still maintain elements of an enumeration.

1php 2 3$array = [1, 2, 3]; 4$array['bar'] = 'baz'; 5$array[] = 4; 

An array from the example above will look like this:

1Array 2( 3 [0] => 1 4 [1] => 2 5 [2] => 3 6 [bar] => baz 7 [3] => 4 8) 

After an associative element was added, PHP automatically assigned a numeric key to the next element, which is equal to the greatest existing numeric key plus one. Note that array keys are indexed from 0 and they don’t determine the order of its elements. PHP is maintaining the array order by its internal pointer.

Because there is no correlation between the array pointer and element keys. We can insert elements with keys which are not sequential:

1php 2 3$array[-10] = 'foo'; 4$array[10] = 4; 5$array[8] = 8; 6$array[] = 2000; 

An array from the example above will look like this:

1Array 2( 3 [-10] => foo 4 [10] => 4 5 [8] => 8 6 [11] => 2000 7) 

PHP automatically assigned a numeric key 11 ( 10+1 ) to the value 2000 .

Printing arrays

To debug a script, it is often needed to output variable values. PHP provides 2 functions which are capable to do this:

  • print_r(): displays information in a way that’s readable by humans; capable to return the information rather than print it (capturing output)
  • var_dump(): displays structured information that includes its type and value; capable of outputting multiple variables at the same time
 1php  2  3$array = [  4 'foo' => 'bar',  5 100 => 'baz',  6];  7  8print_r($array);  9 10$capturedOutput = print_r($array, true); 11echo $capturedOutput; 12 13var_dump($array); 

The example above will output:

 1Array  2(  3 [foo] => bar  4 [100] => baz  5)  6  7Array  8(  9 [foo] => bar 10 [100] => baz 11) 12 13array(2)  14 ["foo"]=> 15 string(3) "bar" 16 [100]=> 17 string(3) "baz" 18> 

Array reconstruction

PHP also provides var_export(), a function which outputs or returns structured information about the given variable. The returned value is a valid PHP code and can be used for reconstruction.

1php 2 3var_export(['Hello', 'World']); 

The example above will output:

1array ( 2 0 => 'Hello', 3 1 => 'World', 4) 

Note missing trailing semicolon.

Accessing array elements

Array elements can be accessed using the square bracket syntax: arrayPhp array index data type .

 1php  2  3$array['greeting'] = 'Hello';  4$array[] = 100;  5$array['beverage'] = [  6 'alcoholic' => 'Wine',  7 'non-alcoholic' => 'Water',  8];  9 10print_r($array); 
 1Array  2(  3 [greeting] => Hello  4 [0] => 100  5 [beverage] => Array  6 (  7 [alcoholic] => Wine  8 [non-alcoholic] => Water  9 ) 10 11) 

Now we can access array elements like this:

1php 2 3var_dump( 4 $array['greeting'], 5 $array[0], 6 $array['beverage']['alcoholic'] 7); 
1string(5) "Hello" 2int(100) 3string(4) "Wine" 

Array elements can be also accessed using curly braces similar to square brackets. Both of them do the same thing (e.g. $array[‘beverage’][‘alcoholic’] and $array ). Elements can be accessed even using mixed syntax (e.g. $array[‘alcoholic’] ).

The square bracket syntax is more commonly used.

Deleting arrays and removing array elements

To remove a key-value pair or delete a whole array use the function unset():

1php 2 3$fruit = ['banana', 'pear', 'blackberry', 'kiwifruit']; 4unset($fruit[0]); 5var_dump($fruit); 

The example above will output:

1array(3)  2 [1]=> 3 string(4) "pear" 4 [2]=> 5 string(10) "blackberry" 6 [3]=> 7 string(9) "kiwifruit" 8> 

Destroying the whole array:

1php 2 3unset($fruit); 4var_dump($fruit); 

The example above will output:

An array can be also removed by overwriting with null :

1php 2 3$vegetable = ['carrot', 'tomato', 'cabbage']; 4$vegetable = null; 

This will have similar effect to the unset().

Determining arrays

Array variables can be determined using is_array() function. This function finds whether the given variable is an array and returns a boolean value.

 1php  2  3$object = new stdClass;  4$array1 = array();  5$array2 = array(1);  6  7var_dump(  8 is_array($object),  9 is_array($array1), 10 is_array($array2) 11); 

The above example will output:

1bool(false) 2bool(true) 3bool(true) 

Determining associative and enumerative arrays

Sometimes it’s needed to determine whether an array has only numeric keys or is associative. PHP does not distinguish between indexed and associative arrays and handles both types in the same way. There is no native function to do this, but there is an elegant solution.

To determine whether an array is associative or not this function can be used:

1php 2 3function is_assoc($array)  4 return (bool) count(array_filter(array_keys($array), 'is_string')); 5> 

Example usage of the is_assoc() function:

1php 2 3$associativeArray = is_assoc(['color' => 'blue', 'number' => 10]); 4$enumerativeArray = is_assoc(['red', 'black', 'yellow']); 5 6var_dump($associativeArray); 7var_dump($enumerativeArray); 

The above code example will output:

The is_assoc() function is using an array function which extracts array keys using the array_keys() function. The output is subsequently filtered using the array_filter() function with the is_string() function as a callback. If at least one of array keys contains string, true is returned or false is returned otherwise. Count of keys containing string is determined using the count() function and subsequently casted to a boolean value using (bool) .

An enumerative array can be determined using negation if this function or creating a new function similar to this one using a different filter callback function.

Comparing arrays

Arrays can be compared using equality operator == or identity operator === :

1php 2 3$array1 = [1, 2, 3]; 4$array2 = [2 => 3, 1 => 2, 0 => 1]; 5$array3 = ['a' => 1, 'b' => 2, 'c' => 3]; 6 7var_dump($array1 == $array2); 8var_dump($array1 === $array2); 9var_dump($array1 == $array3); 
1bool(true) 2bool(false) 3bool(false) 

In both comparison types keys and values are compared. The two arrays are equal when each of them contain the same key-value associations. The identity operator examines also order of an array elements.

Sometimes it’s needed to compare only keys or values. This can be done using same comparison methods as the above and one of the array_keys() or array_values() function:

 1php  2  3$array1 = [1, 2, 3];  4$array2 = [2 => 3, 1 => 2, 0 => 1];  5$array3 = ['a' => 1, 'b' => 2, 'c' => 3];  6$array4 = ['a' => 'black', 'b' => 'red', 'c' => 'green'];  7  8var_dump(array_values($array1) == array_values($array2));  9var_dump(array_values($array1) === array_values($array2)); 10var_dump(array_values($array1) == array_values($array3)); 11var_dump(array_values($array1) === array_values($array3)); 12var_dump(array_keys($array3) === array_keys($array4)); 

The above example will output:

1bool(false) 2bool(false) 3bool(true) 4bool(true) 5bool(true) 

Note that the array_keys() and the array_values() function is reindexing original array keys.

Unravelling and dereferencing arrays

Array elements are often assigned to variables. This can be done using one of accessing methods individually or using list() construct shortcut:

 1php  2  3$array = [  4 'London',  5 '8,416,535',  6 '1,572.00',  7 'England',  8];  9 10list($city, $population, $area, $country) = $array; 11var_dump($city, $population, $area, $country); 
1string(6) "London" 2string(9) "8,416,535" 3string(8) "1,572.00" 4string(7) "England" 

Note that list() assigns values starting with the right-most parameter and works only on numerical keys.

Array elements can be omitted using multiple commas:

1php 2 3list(,,$area1, $country1) = $array; 4list($city2. $country2) = $array; 5 6var_dump($area1, $country1); 7echo '----------' . PHP_EOL; 8var_dump($city2, $country2); 

The above example will output:

1string(8) "1,572.00" 2string(7) "England" 3---------- 4string(6) "London" 5string(7) "England" 

As of PHP 5.4, it is possible to access array members directly when an array is returned by a function. This is known as array dereferencing. As of PHP 5.5, it is also possible to array dereference an array literal.

 1php  2  3function getCity()   4 return [  5 'London',  6 '8,416,535',  7 '1,572.00',  8 'England',  9 ]; 10> 11 12var_dump(getCity()[0]); 13var_dump(getCity()[3]); 14 15echo '----------' . PHP_EOL; 16 17var_dump(['a', 'b', 'c', 'd'][rand(0,3)]); 

The above example will output:

1string(6) "London" 2string(7) "England" 3---------- 4string(1) "a" 

Further reading

Источник

Читайте также:  Java io error socket read timed out
Оцените статью