Php Array (Array)

Source: Internet
Author: User
Tags array definition parse error
Arrays in PHP are actually an ordered ING. Valuing is a type that associates values with keys. This type has been optimized in many aspects, so it can be treated as a real array, or a list (vector), a hash list (an implementation of ing ), the array in the dictionary PHP is actually an ordered ING. Valuing is a type that associates values with keys. This type has been optimized in many aspects, so it can be considered as a real array, or a list (vector), a hash list (an implementation of ING), a dictionary, a set, stack, queue, and more possibilities. Because the value of an array element can be another array, the tree structure and multi-dimensional array are also allowed.

Explanations of these structures are beyond the scope of this manual, but at least one example is provided for each structure. For more information about these structures, we recommend that you refer to other books on this broad topic.


Define array ()

You can use the array () language structure to create an array. It accepts any number of key => value pairs separated by commas.

Array (key => value
// The key is an integer or string.
// Value can be of any type

The comma after the last array unit can be omitted. It is usually used in the definition of a single row array, for example, commonly used array (1, 2) instead of array (1, 2 ,). The last comma is usually retained for the multi-row array definition, which makes it easier to add a new unit.

You can use the short array definition syntax from 5.4 and replace array () ().

Example #1 a simple array

 "Bar", "bar" => "foo",); // starting from PHP 5.4 $ array = ["foo" => "bar ", "bar" => "foo",];?>

The key can be an integer or string. Value can be of any type.

In addition, the key will have the following forced conversion:

A string containing valid integer values is converted to an integer. For example, the key name "8" is actually stored as 8. However, "08" is not forcibly converted because it is not a legal decimal value.

The floating point will also be converted to an integer, meaning that the fractional part of the floating point will be removed. For example, the key name 8.7 is actually stored as 8.

The Boolean value is also converted to an integer. That is, the key name true is actually saved as 1, and the key name false is saved as 0.

Null is converted to a null string, that is, the key name Null is actually stored "".

Arrays and objects cannot be used as key names. Sticking to this will cause a warning: Illegal offset type.

If the same key name is used for multiple cells in the array definition, only the last one is used, and the previous one is overwritten.

Example #2 examples of type forcing and overwriting

  "a",   "1"  => "b",   1.5  => "c",   true => "d",);var_dump($array);?>

The above routine will output:

array(1) {[1]=>string(1) "d"}

In the above example, all the key names are forcibly converted to 1, then each new unit will overwrite the previous value, and only one "d" is left ".

PHP arrays can contain keys of both integer and string types, because PHP does not actually distinguish between index arrays and associated arrays.

If no key name is specified for the given value, the current maximum integer index value is used, and the new key name is the value plus one. If the specified key name already has a value, the value will be overwritten.

Example #3 mixed integer and string key names

  "bar",   "bar" => "foo",   100   => -100,   -100  => 100,);var_dump($array);?>

The above routine will output:

array(4) {["foo"]=>string(3) "bar"["bar"]=>string(3) "foo"[100]=>int(-100)[-100]=>int(100)}

The key is optional. If not specified, PHP automatically uses the previously used maximum integer key name plus 1 as the new key name.

Example #4 index array without a key name


The above routine will output:

array(4) {[0]=>string(3) "foo"[1]=>string(3) "bar"[2]=>string(5) "hallo"[3]=>string(5) "world"}

You can also specify a key name for some cells and leave it blank for others:

Example #5 specify the key name only for some units

  "c",        "d",);var_dump($array);?>

The above routine will output:

array(4) {[0]=>string(1) "a"[1]=>string(1) "b"[6]=>string(1) "c"[7]=>string(1) "d"}

The last value "d" is automatically assigned key 7. This is because the maximum integer key name is 6.

Use square brackets to access array units

Array units can be accessed using the array [key] syntax.

Example #6 access an array unit

  "bar",   42    => 24,   "multi" => array(        "dimensional" => array(            "array" => "foo"        )   )); var_dump($array["foo"]);var_dump($array[42]);var_dump($array["multi"]["dimensional"]["array"]);?>

The above routine will output:

string(3) "bar"int(24)string(3) "foo"


Square brackets and curly brackets can be used to access array units (for example, $ array [42] and $ array {42} have the same effect in the preceding example ).

From PHP 5.4 onwards, you can use arrays to indirectly reference the results of function or method calls. You can only use one temporary variable.

From PHP 5.5, an array prototype can be indirectly referenced using arrays.

Example #7 indirect array reference



Trying to access an undefined array key name is the same as accessing any undefined variable: it will lead to an error message at the E_NOTICE level and the result is NULL.

Create/modify with square brackets

You can explicitly set the value to modify an existing array.

This is achieved by specifying a key name in square brackets to assign values to the array. You can also omit the key name. in this case, add an empty square brackets ([]) to the variable name.

$ Arr [key] = value;
$ Arr [] = value;
// The key can be integer or string.
// Value can be of any type

If $ arr does not exist, a new method is created, which is another method for creating an array. This is not encouraged, because if $ arr already contains a value (such as a string from the request variable), this value is retained, and [] actually represents the string access operator. The best way to initialize a variable is to assign a value directly ..

To modify a value, assign a new value to the unit by its key name. To delete a key-value pair, call the unset () function.

  1, 12 => 2);$arr[] = 56;    // This is the same as $arr[13] = 56;               // at this point of the script$arr["x"] = 42; // This adds a new element to               // the array with key "x"unset($arr[5]); // This removes the element from the arrayunset($arr);    // This deletes the whole array?>


As mentioned above, if square brackets are provided but no key name is specified, the current maximum integer index value is taken. the new key name is the value plus 1 (but the minimum value is 0 ). If no integer index exists, the key name is 0.

Note that the maximum integer key used here is not necessarily in the array currently. It only needs to exist after the index is re-generated in the last array. The following is an example:

 $ Value) {unset ($ array [$ I]);} print_r ($ array); // add a unit (note that the new key name is 5, instead of what you might think is 0) $ array [] = 6; print_r ($ array); // re-index: $ array = array_values ($ array ); $ array [] = 7; print_r ($ array);?>

The above routine will output:

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

Practical functions

There are many array functions. For more information, see the array functions section.


The unset () function allows you to delete a key from an array. However, note that the array will not rebuild the index. If you want to delete and recreate the index, you can use the array_values () function.


?php$a = array(1 => 'one', 2 => 'two', 3 => 'three');unset($a[2]);/* will produce an array that would have been defined as  $a = array(1 => 'one', 3 => 'three');  and NOT  $a = array(1 => 'one', 2 =>'three');*/ $b = array_values($a);// Now $b is array(0 => 'one', 1 =>'three')?>

The foreach control structure is specially used for arrays. It provides a simple method to traverse arrays.

Array and nothing

Why is $ foo [bar] incorrect?

Always put quotation marks on the array index represented by a string. For example, use $ foo ['bar'] instead of $ foo [bar]. But why? You may have seen the following syntax in the old script:


This is wrong, but it can run normally. So why is it wrong? The reason is that this code has an undefined constant (bar) instead of a string ('bar'-note quotation marks), and PHP may define this constant later, unfortunately, your code has the same name. It can run because PHP automatically converts a bare string (a string without quotation marks and does not conform to any known symbol) into a normal string whose value is the bare string. For example, if no constant is defined as bar, PHP replaces it with 'bar' and uses it.

Note: this does not mean that the key name is always enclosed in quotation marks. You do not need to quote the key name constants or variables. otherwise, PHP cannot parse them.


The above routine will output:

Checking 0:
Notice: Undefined index: $ I in/path/to/script.html on line 9
Good: 1
Notice: Undefined index: $ I in/path/to/script.html on line 11
Good: 1

Checking 1:
Notice: Undefined index: $ I in/path/to/script.html on line 9
Good: 2
Notice: Undefined index: $ I in/path/to/script.html on line 11
Good: 2

More examples of this behavior are as follows:

  'apple', 'veggie' => 'carrot'); // Correctprint $arr['fruit'];  // appleprint $arr['veggie']; // carrot // Incorrect.  This works but also throws a PHP error of level E_NOTICE because// of an undefined constant named fruit//// Notice: Use of undefined constant fruit - assumed 'fruit' in...print $arr[fruit];    // apple // This defines a constant to demonstrate what's going on.  The value 'veggie'// is assigned to a constant named fruit.define('fruit', 'veggie'); // Notice the difference nowprint $arr['fruit'];  // appleprint $arr[fruit];    // carrot // The following is okay, as it's inside a string. Constants are not looked for// within strings, so no E_NOTICE occurs hereprint "Hello $arr[fruit]";      // Hello apple // With one exception: braces surrounding arrays within strings allows constants// to be interpretedprint "Hello {$arr[fruit]}";    // Hello carrotprint "Hello {$arr['fruit']}";  // Hello apple // This will not work, and will result in a parse error, such as:// Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING'// This of course applies to using superglobals in strings as wellprint "Hello $arr['fruit']";print "Hello $_GET['foo']"; // Concatenation is another optionprint "Hello " . $arr['fruit']; // Hello apple?>

When error_reporting is enabled to display E_NOTICE-level errors (set it to E_ALL), these errors are displayed. By default, error_reporting is disabled and not displayed.

As defined in the syntax section, there must be an expression between square brackets ("[" and. This means you can write it like this:


This is an example of using the function return value as an array index. PHP can also use known constants, which may have been seen before:


Note that E_ERROR is also a valid identifier, just like bar in the first example. However, the previous example is actually the same as the following statement:


Because E_ERROR is equal to 1, and so on.

So why is this not good?

Maybe one day, the PHP development team may want to add a new constant or keyword, or users may want to introduce new constants in their own programs in the future, it will be troublesome. For example, empty and default cannot be used as they are reserved words.

Note: Once again, it is legal not to enclose the index in double quotation marks. Therefore, "$ foo [bar]" is legal (the original "legal" is valid. In actual tests, this can indeed access the element of the array, but a notice with a constant undefined will be reported. In any case, we strongly recommend that you do not use $ foo [bar], but use $ foo ['bar'] to access elements in the array. -- Haohappy note ). For more information, see the preceding examples and explanations in variable parsing in strings.

Convert to array

For any integer, float, string, boolean, and resource types, if you convert a value to an array, an array with only one element is obtained, and its subscript is 0, this element is the value of this scalar. In other words, (array) $ scalarValue is exactly the same as array ($ scalarValue.

If an object type is converted to array, the result is an array, and its unit is the attribute of the object. The key name is the member variable name, but there are several exceptions: the integer attribute is not accessible; the class name prefix is added before the private variable; the variable prefix is added before the protection variable. Each of these prefixes has a NULL character. This will lead to some unpredictable behaviors:


In the preceding example, two keys are named 'A', but one of them is '\ 0A \ 0a '.

Convert NULL to array to get an empty array.


You can use the array_diff () and array operators to compare arrays.


The array types in PHP are used in many ways. The following are some examples:

  'red',           'taste' => 'sweet',           'shape' => 'round',           'name'  => 'apple',           4        // key will be 0         ); $b = array('a', 'b', 'c'); // . . .is completely equivalent with this:$a = array();$a['color'] = 'red';$a['taste'] = 'sweet';$a['shape'] = 'round';$a['name']  = 'apple';$a[]        = 4;        // key will be 0 $b = array();$b[] = 'a';$b[] = 'b';$b[] = 'c'; // After the above code is executed, $a will be the array// array('color' => 'red', 'taste' => 'sweet', 'shape' => 'round',// 'name' => 'apple', 0 => 4), and $b will be the array// array(0 => 'a', 1 => 'b', 2 => 'c'), or simply array('a', 'b', 'c').?>

Example #8 use array ()

  4,             'OS'         => 'Linux',             'lang'       => 'english',             'short_tags' => true           );// strictly numerical keys$array = array( 7,               8,               0,               156,               -10             );// this is the same as array(0 => 7, 1 => 8, ...) $switching = array(         10, // key = 0                   5    =>  6,                   3    =>  7,                   'a'  =>  4,                           11, // key = 6 (maximum of integer-indices was 5)                   '8'  =>  2, // key = 8 (integer!)                   '02' => 77, // key = '02'                   0    => 12  // the value 10 will be overwritten by 12                 );// empty array$empty = array();?>

Example #9 set


The above routine will output:

Do you like red?
Do you like blue?
Do you like green?
Do you like yellow?

Directly changing the array value can be achieved through reference transfer from PHP 5. The previous version requires a work und:

Example #10 Change the unit in a loop

  $color) {   $colors[$key] = strtoupper($color);} print_r($colors);?>

The above routine will output:

Array([0] => RED[1] => BLUE[2] => GREEN[3] => YELLOW)

In this example, an array with subscript starting from 1 is generated.

Example #11 subscript array starting from 1

  'January', 'February', 'March');print_r($firstquarter);?>

The above routine will output:

[1] => 'January'
[2] => 'February'
[3] => 'March'

Example #12 fill in the array


Arrays are ordered. You can also use different sorting functions to change the order. For more information, see array functions. You can use the count () function to calculate the number of elements in the array.

Example #13 sorting arrays


Because the value in the array can be any value, but also another array. This can generate recursive or multi-dimensional arrays.

Example #14 recursive and multi-dimensional arrays

  array ( "a" => "orange",                                      "b" => "banana",                                      "c" => "apple"                                    ),                 "numbers" => array ( 1,                                      2,                                      3,                                      4,                                      5,                                      6                                    ),                 "holes"   => array (      "first",                                      5 => "second",                                           "third"                                    )               ); // Some examples to address values in the array aboveecho $fruits["holes"][5];    // prints "second"echo $fruits["fruits"]["a"]; // prints "orange"unset($fruits["holes"][0]);  // remove "first" // Create a new multi-dimensional array$juices["apple"]["green"] = "good";?>

The value assignment of an Array always involves copying values. Use the reference operator to copy an array through reference.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.