PHP Arrays (Array)

Source: Internet
Author: User
Tags array definition parse error php error
The array in PHP is actually an ordered map. A map is a type that associates values to the keys. This type is optimized in many ways, so it can be used as a real array, or as a list (vector), a hash (an implementation of a mapping), a dictionary, a collection, a stack, a queue, and more possibilities. Because the value of an array element can also be another array, the tree structure and the multidimensional array are also allowed.

Explaining these structures is beyond the scope of this manual, but at least one example is provided for each structure. For more information on these structures, it is recommended to refer to other works on this broad topic.

Grammar

Defines an array of arrays ()

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

Array (key = value
, ...
)
The key (key) is an integer or string
Values (value) can be any type of value

The comma after the last array element can be omitted. Typically used in a single-line array definition, such as a common array (1, 2) instead of an array (1, 2,). The last comma is usually reserved for multi-line array definitions, which makes it easier to add a new cell.

You can use the short array definition syntax since 5.4 to replace array () with [].

Example #1 a simple array

<?php$array = Array (   "foo" = "Bar",   "bar" = "foo",);//since PHP 5.4 $array = [   "foo" = "Bar", 
   "Bar" = "foo",];? >

Key can be an integer or string. Value can be of any type.

In addition, key will have the following casts:

A string containing a valid integer value is converted to an integral type. For example, the key name "8" will actually be stored as 8. However, "08" does not cast because it is not a valid decimal value.

Floating-point numbers are also converted to integers, meaning that their fractional parts are removed. For example, key name 8.7 will actually be stored as 8.

Boolean values are also converted to integral types. That is, the key name true is actually stored as 1 and the key name false is stored as 0.

Null is converted to an empty string, that is, the key name null is actually stored as "".

Arrays and objects cannot be used as key names. Insisting on doing so will result in a warning: illegal offset type.

If more than one cell in the array definition uses the same key name, only the last one is used, and the previous is overwritten.

Example #2 type coercion and overrides example

<?php$array = Array (   1 =    "A",   "1"  = "B",   1.5 =  "C",   true = "D",); var_ Dump ($array);? >

The above routines will output:

Array (1) {[1]=>string (1) "D"}

All of the key names in the previous example are cast to 1, each new cell overwrites the previous value, and the last remaining is only one "D".

PHP arrays can contain both integer and string key names, because PHP does not actually differentiate between indexed and associative arrays.

If no key name is specified for the given value, the current largest integer index value is taken, and the new key name is the value plus one. If the specified key name already has a value, the value is overwritten.

Example #3 mixed Integer and string key names

<?php$array = Array (   "foo" = "Bar",   "bar" = "foo",   -100,   -100  = Var_dump ($array);? >

The above routines will output:

Array (4) {["foo"]=>string (3) "Bar" ["Bar"]=>string (3) "Foo" [100]=>int ( -100) [ -100]=>int (100)}

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

Example #4 an indexed array without a key name

<?php$array = Array ("foo", "Bar", "Hallo", "World"); Var_dump ($array);? >

The above routines will output:

Array (4) {[0]=>string (3) "Foo" [1]=>string (3) "Bar" [2]=>string (5) "Hallo" [3]=>string (5) "World"}

You can also specify key names for some cells and empty them for others:

Example #5 Specify key names only for partial cells

<?php$array = Array (        "a",        "B",   6 = "C",        "D",); Var_dump ($array);? >

The above routines will output:

Array (4) {[0]=>string (1) "A" [1]=>string (1) "B" [6]=>string (1) "C" [7]=>string (1) "D"}

You can see that the last value "D" is automatically assigned the key name 7. This is due to the previous maximum integer key name is 6.

Accessing array cells with square brackets syntax

Array cells can be accessed through the Array[key] syntax.

Example #6 access to array cells

<?php$array = Array (   "foo" + "Bar", "multi" = "=" =   Array (        "dimensional" = Array (            "Array" = "foo"))   , Var_dump ($array ["foo"]), Var_dump ($array []), Var_dump ($array ["Multi" ["Dimensional"] ["array"]);? >

The above routines will output:

String (3) "Bar" int (3) "Foo"

Note:

Square brackets and braces can be used interchangeably to access array cells (for example $array [42] and $array {42} have the same effect in the previous example).

The result of a function or method call can be referenced indirectly from PHP 5.4 using an array. Only one temporary variable can be passed before.

An array prototype can be referenced indirectly from PHP 5.5 using an array.

Example #7 Array Indirect reference

<?phpfunction GetArray () {   return Array (1, 2, 3);}//on PHP 5.4$secondelement = GetArray () [1];//previously$tmp = GetArray (); $secondElement = $tmp [1];//orlist (, $secondElement) = GetArray (); >

Note:

Attempting to access an undefined array key name is the same as accessing any undefined variable: it causes the E_notice level error message and the result is NULL.

New/modified with square brackets syntax

You can modify an existing array by explicitly setting its value.

This is done by assigning a value to the array by specifying the key name within the square brackets. You can also omit the key name, in which case a pair of empty brackets ([]) are added to the variable name.

$arr [key] = value;
$arr [] = value;
Key can be an integer or string
Value can be of any type

If the $arr does not already exist, a new one will be created, which is another way to create a new array. This is not encouraged, however, because if the $arr already contains a value (such as a string from a request variable) then this value is preserved and [] actually represents the string access operator. The best way to initialize a variable is to assign it directly.

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

<?php$arr = Array (5 = 1, + 2); $arr [] = up;    This is the same as $arr [] = a.               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?>

Note:

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

Note that the maximum integer key name used here is not necessarily present in the array. It just has to exist after the last array rebuild index. Use the following example to illustrate:

<?php//creates a simple array of $array = Array (1, 2, 3, 4, 5);p Rint_r ($array);//delete all the elements in it now, but keep the array itself unchanged: foreach ($array as $i = = $va Lue) {   unset ($array [$i]);} Print_r ($array);//Add a unit (note that the new key name is 5, not what you might think 0) $array [] = 6;print_r ($array);//re-index: $array = array_values ($array); Array[] = 7;print_r ($array);? >

The above routines will output:

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

Utility functions

There are many functions that manipulate arrays, see the section on array functions.

Note:

The unset () function allows you to delete a key in an array. However, be aware that the array will not rebuild the index. If you need to rebuild the index after deletion, you can use the Array_values () function.

<

php$a = Array (1 = ' one ', 2 = ' one ', 3 = ' three '), unset ($a [2]);/* would produce an array that would has been D efined  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 = ' t Hree ')?>

The foreach control structure is used exclusively for arrays. It provides a simple way to iterate through an array.

Array of what to do and what not to do

Why is the $foo [bar] wrong?

You should always enclose the array index with a string representation. For example, use $foo [' Bar '] instead of $foo [bar]. But why? You may have seen the following syntax in the old script:

<?php$foo[bar] = ' enemy '; Echo $foo [bar];//etc?>

This is wrong, but it will work. So why was it wrong? The reason is that there is an undefined constant (bar) in this code instead of a string (' bar '-note quotes), and PHP may define this constant later, but unfortunately your code has the same name. It works because PHP automatically converts a bare string (a string without a quotation mark) to a normal string whose value is the bare string, which does not correspond to any known symbol. For example, if no constant is defined as bar,php it will be substituted for ' bar ' and used.

Note: This does not mean that you always enclose the key name in quotation marks. You do not need to enclose the key name as a constant or a variable, otherwise it will make PHP unable to parse it.

<?phperror_reporting (E_all); Ini_set (' display_errors ', true); Ini_set (' html_errors ', false);//Simple array:$ Array = Array (1, 2), $count = count ($array), for ($i = 0; $i < $count; $i + +) {   echo "\nchecking $i: \ n";   echo "Bad:". $array [' $i ']. "\ n";   echo "Good:". $array [$i]. "\ n";   echo "bad: {$array [' $i ']}\n";   echo "good: {$array [$i]}\n";}? >

The above routines will output:

Checking 0:
notice:undefined index: $i in/path/to/script.html on line 9
Bad:
Good:1
notice:undefined index: $i in/path/to/script.html on line 11
Bad:
Good:1

Checking 1:
notice:undefined index: $i in/path/to/script.html on line 9
Bad:
Good:2
notice:undefined index: $i in/path/to/script.html on line 11
Bad:
Good:2

More examples of this behavior are shown:

<?php//Show all errorserror_reporting (E_all); $arr = Array (' fruit ' = ' apple ', ' veggie ' = ' carrot ');  Correctprint $arr [' Fruit ']; Appleprint $arr [' Veggie '];  Carrot//incorrect.  This works but also throws a PHP error of the level E_notice because//of a undefined constant named fruit////notice:use of Undefined constant fruit-assumed ' fruit ' in ...    Print $arr [fruit];  Apple//This defines a constant-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 is 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 won't work, and would result in a parse error, such as://parse Error:parse error, expecting t_string ' or t_v Ariable ' or t_num_string '//This is course applies to using superglobals in strings as Wellprint "Hello $arr [' Fruit ']";p ri NT "Hello $_get[' foo ']"; Concatenation is another Optionprint "Hello". $arr [' Fruit ']; Hello apple?>

You will see these errors when you open error_reporting to display E_notice level errors (set them to E_all). By default error_reporting is turned off and does not show these.

As specified in the syntax section, there must be an expression between square brackets ("[" and "]"). This means that you can write:

<?phpecho $arr [SomeFunc ($bar)];? >

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

<?php$error_descriptions[e_error]   = "A fatal error has occured"; $error _descriptions[e_warning] = "PHP issued A Warning "; $error _descriptions[e_notice]  =" This was just an informal NOTICE ";? >

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

<?PHP$ERROR_DESCRIPTIONS[1] = "A fatal error has occured"; $error _descriptions[2] = "PHP issued A warning"; $error _descr IPTIONS[8] = "Just an informal notice";? >

Because E_error equals 1, and so on.

So why not do it well?

Perhaps one day, the PHP development team might want to add a constant or keyword, or the user might want to introduce new constants into their own programs later, and that would be a problem. For example, it is not possible to use empty and default two words, because they are reserved words.

Note: Once again, in a double-quoted string, it is legal to not enclose the index in quotation marks, so "$foo [bar]" is legal (the original text of "valid" is valid. In the actual test, this can actually access the element of the array, but it will report a constant undefined notice. In any case, it is strongly recommended not to use the $foo [bar] notation, but to use $foo [' Bar '] to access the elements in the array. --haohappy note). As for why see the above example and the explanation of the variable parsing in the string.

Converting to arrays

For any Integer,float,string,boolean and resource type, if you convert a value to an array, you will get a list of only one element, with a subscript of 0, which is the value of this scalar. In other words, the (array) $scalarValue is exactly the same as array ($scalarValue).

If an object type is converted to array, the result is an array whose cells are the properties of the object. The key name is the member variable name, but there are several exceptions: the integer attribute is not accessible, and the private variable is preceded by a class name prefix, and a ' * ' prefix is added before the protection variable. Each of these prefixes has a NULL character before and after each. This can lead to unpredictable behavior:

<?php class A {   private $A;//This would become ' \0a\0a '} class B extends A {   private $A;//This would become ' \0b\0a ' public   $AA;//This would become ' AA '} var_dump ((array) new B ());? >

There are two keys named ' AA ' in the previous meeting, but one of them is actually ' \0a\0a '.

Converting NULL to array will get an empty array.

Comparison

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

Example

There are a lot of uses for array types in PHP. Here are some examples:

<?php//this: $a = array (' Color ' = ' red ',           ' taste ' = ' sweet ',           ' shape ' = ' round ', '           name '  =& Gt ' Apple ',           4        //key would be 0         ); $b = Array (' A ', ' B ', ' C ');//... is completely equivalent with this: $a = Arra Y (); $a [' color '] = ' red '; $a [' taste '] = ' sweet '; $a [' shape '] = ' round '; $a [' name ']  = ' Apple '; $a []        = 4;        Key would be 0 $b = array (), $b [] = ' a '; $b [] = ' B '; $b [] = ' C '; After the above code is executed, $a'll be the array//array (' Color ' + ' red ', ' taste ' = ' sweet ', ' shape ' => ; ' Round ',//' name ' = ' Apple ', 0 = 4), and $b'll be the array//array (0 = ' a ', 1 = ' B ', 2 = ' C '), or S imply array (' A ', ' B ', ' C ').? >

Example #8 using Array ()

<?php//array as (property-) Map$map = Array (' version ' = =    4,             ' OS ' = '         Linux ',             ' lang '       = > ' 中文版 ',             ' short_tags ' + true           );//strictly numerical Keys$array = Array (7,               8,               0,               156,< C10/>-10);//This is the             same as array (0 = 7, 1 = 8, ...) $switching = Array (         ten,//key = 0                   5
  =>  6,                   3    =  7,                   ' a '  =  4, one                           ,//key = 6 (maximum of integer-indices was 5)                   ' 8 ' = =  2,//key = 8 (integer!)                   ' ' = ',//key = ' 0 = '/' The value of ' is overwritten by ';//                 empty array$empt y = array ();? >

Example #9 Collection

<?php$colors = Array (' Red ', ' blue ', ' green ', ' yellow '); foreach ($colors as $color) {   echo "Do you like $color? \ n";}?>

The above routines will output:

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

Changing the value of an array directly from PHP 5 can be done by reference passing. The previous version requires a workaround:

Example #10 Changing cells in the loop

<?php//php 5foreach ($colors as & $color) {   $color = Strtoupper ($color);} Unset ($color);  /* Ensure that following writes To$color won't modify the last array element *//workaround for older Versionsforeach ($colors as $key = $color) {   $colors [$key] = Strtoupper ($color);} Print_r ($colors);? >

The above routines will output:

Array ([0] = red[1] = blue[2] = green[3] = YELLOW)

This example generates an array that starts with a subscript of 1.

Example #11 Subscript array starting from 1

<?php$firstquarter  = Array (1 = ' January ', ' February ', ' March ');p Rint_r ($firstquarter);? >

The above routines will output:

Array
(
[1] = ' January '
[2] = ' February '
[3] = ' March '
)

Example #12 padding Array

<?php//fill an array with all items from a directory$handle = Opendir ('. '); while (false!== ($file = Readdir ($handle))) {   $files [] = $file;} Closedir ($handle);? >

The array is 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 count the number of elements in the array.

Example #13 Array Sorting

<?phpsort ($files);p rint_r ($files);? >

Because the values in the array can be any value or another array. This can result in recursive or multidimensional arrays.

Example #14 recursive and multidimensional arrays

<?php$fruits = Array ("fruits" = = Array ("A" = "orange", "B" and "=" Bana Na "," 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 assignment of arrays (array) always involves a copy of the value. Use the reference operator to copy an array by reference.

<?PHP$ARR1 = Array (2, 3), $arr 2 = $arr 1; $arr 2[] = 4; $arr 2 is changed,            //$arr 1 was still array (2, 3) $arr 3 = & $arr 1; $arr 3[] = 4;//Now $arr 1 and $arr 3 is the same? >
  • 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: info-contact@alibabacloud.com 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.