mirror of
https://github.com/sigmasternchen/php-doc-en
synced 2025-03-15 16:38:54 +00:00

git-svn-id: https://svn.php.net/repository/phpdoc/en/trunk@332515 c90b9560-bf6c-de11-be94-00142212c4b1
1122 lines
29 KiB
XML
1122 lines
29 KiB
XML
<?xml version="1.0" encoding="utf-8"?>
|
|
<!-- $Revision$ -->
|
|
<sect1 xml:id="language.types.array">
|
|
<title>Arrays</title>
|
|
|
|
<para>
|
|
An <type>array</type> in PHP is actually an ordered map. A map is a type that
|
|
associates <emphasis>values</emphasis> to <emphasis>keys</emphasis>. This type
|
|
is optimized for several different uses; it can be treated as an array,
|
|
list (vector), hash table (an implementation of a map), dictionary,
|
|
collection, stack, queue, and probably more. As <type>array</type> values can
|
|
be other <type>array</type>s, trees and multidimensional <type>array</type>s
|
|
are also possible.
|
|
</para>
|
|
|
|
<para>
|
|
Explanation of those data structures is beyond the scope of this manual, but
|
|
at least one example is provided for each of them. For more information, look
|
|
towards the considerable literature that exists about this broad topic.
|
|
</para>
|
|
|
|
<sect2 xml:id="language.types.array.syntax">
|
|
<title>Syntax</title>
|
|
|
|
<sect3 xml:id="language.types.array.syntax.array-func">
|
|
<title>Specifying with <function>array</function></title>
|
|
|
|
<para>
|
|
An <type>array</type> can be created using the <function>array</function>
|
|
language construct. It takes any number of comma-separated
|
|
<literal><replaceable>key</replaceable> => <replaceable>value</replaceable></literal> pairs
|
|
as arguments.
|
|
</para>
|
|
|
|
<synopsis>
|
|
array(
|
|
<optional><replaceable>key</replaceable> => </optional><replaceable>value</replaceable>,
|
|
<optional><replaceable>key2</replaceable> => </optional><replaceable>value2</replaceable>,
|
|
<optional><replaceable>key3</replaceable> => </optional><replaceable>value3</replaceable>,
|
|
...
|
|
)</synopsis>
|
|
<!-- Do not fix the whitespace for the synopsis end element. A limitation of PhD prevents proper trimming -->
|
|
|
|
<para>
|
|
The comma after the last array element is optional and can be omitted. This is usually done
|
|
for single-line arrays, i.e. <literal>array(1, 2)</literal> is preferred over
|
|
<literal>array(1, 2, )</literal>. For multi-line arrays on the other hand the trailing comma
|
|
is commonly used, as it allows easier addition of new elements at the end.
|
|
</para>
|
|
|
|
<para>
|
|
As of PHP 5.4 you can also use the short array syntax, which replaces
|
|
<literal>array()</literal> with <literal>[]</literal>.
|
|
</para>
|
|
|
|
<example>
|
|
<title>A simple array</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
$array = array(
|
|
"foo" => "bar",
|
|
"bar" => "foo",
|
|
);
|
|
|
|
// as of PHP 5.4
|
|
$array = [
|
|
"foo" => "bar",
|
|
"bar" => "foo",
|
|
];
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</example>
|
|
|
|
<para>
|
|
The <replaceable>key</replaceable> can either be an <type>integer</type>
|
|
or a <type>string</type>. The <replaceable>value</replaceable> can be
|
|
of any type.
|
|
</para>
|
|
|
|
<para>
|
|
Additionally the following <replaceable>key</replaceable> casts will occur:
|
|
<itemizedlist>
|
|
<listitem>
|
|
<simpara>
|
|
<type>String</type>s containing valid <type>integer</type>s will be cast to the
|
|
<type>integer</type> type. E.g. the key <literal>"8"</literal> will actually be
|
|
stored under <literal>8</literal>. On the other hand <literal>"08"</literal> will
|
|
not be cast, as it isn't a valid decimal integer.
|
|
</simpara>
|
|
</listitem>
|
|
<listitem>
|
|
<simpara>
|
|
<type>Float</type>s are also cast to <type>integer</type>s, which means that the
|
|
fractional part will be truncated. E.g. the key <literal>8.7</literal> will actually
|
|
be stored under <literal>8</literal>.
|
|
</simpara>
|
|
</listitem>
|
|
<listitem>
|
|
<simpara>
|
|
<type>Bool</type>s are cast to <type>integer</type>s, too, i.e. the key
|
|
<literal>true</literal> will actually be stored under <literal>1</literal>
|
|
and the key <literal>false</literal> under <literal>0</literal>.
|
|
</simpara>
|
|
</listitem>
|
|
<listitem>
|
|
<simpara>
|
|
<type>Null</type> will be cast to the empty string, i.e. the key
|
|
<literal>null</literal> will actually be stored under <literal>""</literal>.
|
|
</simpara>
|
|
</listitem>
|
|
<listitem>
|
|
<simpara>
|
|
<type>Array</type>s and <type>object</type>s <emphasis>can not</emphasis> be used as keys.
|
|
Doing so will result in a warning: <literal>Illegal offset type</literal>.
|
|
</simpara>
|
|
</listitem>
|
|
</itemizedlist>
|
|
</para>
|
|
|
|
<para>
|
|
If multiple elements in the array declaration use the same key, only the last one
|
|
will be used as all others are overwritten.
|
|
</para>
|
|
|
|
<example>
|
|
<title>Type Casting and Overwriting example</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
$array = array(
|
|
1 => "a",
|
|
"1" => "b",
|
|
1.5 => "c",
|
|
true => "d",
|
|
);
|
|
var_dump($array);
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
&example.outputs;
|
|
<screen>
|
|
<![CDATA[
|
|
array(1) {
|
|
[1]=>
|
|
string(1) "d"
|
|
}
|
|
]]>
|
|
</screen>
|
|
<para>
|
|
As all the keys in the above example are cast to <literal>1</literal>, the value will be overwritten
|
|
on every new element and the last assigned value <literal>"d"</literal> is the only one left over.
|
|
</para>
|
|
</example>
|
|
|
|
<para>
|
|
PHP arrays can contain <type>integer</type> and <type>string</type> keys at the same time
|
|
as PHP does not distinguish between indexed and associative arrays.
|
|
</para>
|
|
|
|
<example>
|
|
<title>Mixed <type>integer</type> and <type>string</type> keys</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
$array = array(
|
|
"foo" => "bar",
|
|
"bar" => "foo",
|
|
100 => -100,
|
|
-100 => 100,
|
|
);
|
|
var_dump($array);
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
&example.outputs;
|
|
<screen>
|
|
<![CDATA[
|
|
array(4) {
|
|
["foo"]=>
|
|
string(3) "bar"
|
|
["bar"]=>
|
|
string(3) "foo"
|
|
[100]=>
|
|
int(-100)
|
|
[-100]=>
|
|
int(100)
|
|
}
|
|
]]>
|
|
</screen>
|
|
</example>
|
|
|
|
<para>
|
|
The <replaceable>key</replaceable> is optional. If it is not specified, PHP will
|
|
use the increment of the largest previously used <type>integer</type> key.
|
|
</para>
|
|
|
|
<example>
|
|
<title>Indexed arrays without key</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
$array = array("foo", "bar", "hello", "world");
|
|
var_dump($array);
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
&example.outputs;
|
|
<screen>
|
|
<![CDATA[
|
|
array(4) {
|
|
[0]=>
|
|
string(3) "foo"
|
|
[1]=>
|
|
string(3) "bar"
|
|
[2]=>
|
|
string(5) "hello"
|
|
[3]=>
|
|
string(5) "world"
|
|
}
|
|
]]>
|
|
</screen>
|
|
</example>
|
|
|
|
<para>
|
|
It is possible to specify the key only for some elements and leave it out for others:
|
|
</para>
|
|
|
|
<example>
|
|
<title>Keys not on all elements</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
$array = array(
|
|
"a",
|
|
"b",
|
|
6 => "c",
|
|
"d",
|
|
);
|
|
var_dump($array);
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
&example.outputs;
|
|
<screen>
|
|
<![CDATA[
|
|
array(4) {
|
|
[0]=>
|
|
string(1) "a"
|
|
[1]=>
|
|
string(1) "b"
|
|
[6]=>
|
|
string(1) "c"
|
|
[7]=>
|
|
string(1) "d"
|
|
}
|
|
]]>
|
|
</screen>
|
|
<para>
|
|
As you can see the last value <literal>"d"</literal> was assigned the key
|
|
<literal>7</literal>. This is because the largest integer key before that
|
|
was <literal>6</literal>.
|
|
</para>
|
|
</example>
|
|
</sect3>
|
|
|
|
<sect3 xml:id="language.types.array.syntax.accessing">
|
|
<title>Accessing array elements with square bracket syntax</title>
|
|
|
|
<para>
|
|
Array elements can be accessed using the <literal>array[key]</literal> syntax.
|
|
</para>
|
|
|
|
<example>
|
|
<title>Accessing array elements</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
$array = array(
|
|
"foo" => "bar",
|
|
42 => 24,
|
|
"multi" => array(
|
|
"dimensional" => array(
|
|
"array" => "foo"
|
|
)
|
|
)
|
|
);
|
|
|
|
var_dump($array["foo"]);
|
|
var_dump($array[42]);
|
|
var_dump($array["multi"]["dimensional"]["array"]);
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
&example.outputs;
|
|
<screen>
|
|
<![CDATA[
|
|
string(3) "bar"
|
|
int(24)
|
|
string(3) "foo"
|
|
]]>
|
|
</screen>
|
|
</example>
|
|
|
|
<note>
|
|
<para>
|
|
Both square brackets and curly braces can be used interchangeably
|
|
for accessing array elements (e.g. <literal>$array[42]</literal> and <literal>$array{42}</literal> will
|
|
both do the same thing in the example above).
|
|
</para>
|
|
</note>
|
|
|
|
<para>
|
|
As of PHP 5.4 it is possible to array dereference the result of a function
|
|
or method call directly. Before it was only possible using a temporary
|
|
variable.
|
|
</para>
|
|
|
|
<para>
|
|
As of PHP 5.5 it is possible to array dereference an array literal.
|
|
</para>
|
|
|
|
<example>
|
|
<title>Array dereferencing</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
function getArray() {
|
|
return array(1, 2, 3);
|
|
}
|
|
|
|
// on PHP 5.4
|
|
$secondElement = getArray()[1];
|
|
|
|
// previously
|
|
$tmp = getArray();
|
|
$secondElement = $tmp[1];
|
|
|
|
// or
|
|
list(, $secondElement) = getArray();
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</example>
|
|
|
|
<note>
|
|
<para>
|
|
Attempting to access an array key which has not been defined is
|
|
the same as accessing any other undefined variable:
|
|
an <constant>E_NOTICE</constant>-level error message will be
|
|
issued, and the result will be &null;.
|
|
</para>
|
|
</note>
|
|
</sect3>
|
|
|
|
<sect3 xml:id="language.types.array.syntax.modifying">
|
|
<title>Creating/modifying with square bracket syntax</title>
|
|
|
|
<para>
|
|
An existing <type>array</type> can be modified by explicitly setting values
|
|
in it.
|
|
</para>
|
|
|
|
<para>
|
|
This is done by assigning values to the <type>array</type>, specifying the
|
|
key in brackets. The key can also be omitted, resulting in an empty pair of
|
|
brackets (<literal>[]</literal>).
|
|
</para>
|
|
|
|
<synopsis>
|
|
$arr[<replaceable>key</replaceable>] = <replaceable>value</replaceable>;
|
|
$arr[] = <replaceable>value</replaceable>;
|
|
// <replaceable>key</replaceable> may be an <type>integer</type> or <type>string</type>
|
|
// <replaceable>value</replaceable> may be any value of any type</synopsis>
|
|
|
|
<para>
|
|
If <varname>$arr</varname> doesn't exist yet, it will be created, so this is
|
|
also an alternative way to create an <type>array</type>. This practice is
|
|
however discouraged because if <varname>$arr</varname> already contains
|
|
some value (e.g. <type>string</type> from request variable) then this
|
|
value will stay in the place and <literal>[]</literal> may actually stand
|
|
for <link linkend="language.types.string.substr">string access
|
|
operator</link>. It is always better to initialize variable by a direct
|
|
assignment.
|
|
</para>
|
|
|
|
<para>
|
|
To change a certain
|
|
value, assign a new value to that element using its key. To remove a
|
|
key/value pair, call the <function>unset</function> function on it.
|
|
</para>
|
|
|
|
<informalexample>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
$arr = array(5 => 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 array
|
|
|
|
unset($arr); // This deletes the whole array
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</informalexample>
|
|
|
|
<note>
|
|
<para>
|
|
As mentioned above, if no key is specified, the maximum of the existing
|
|
<type>integer</type> indices is taken, and the new key will be that maximum
|
|
value plus 1 (but at least 0). If no <type>integer</type> indices exist yet, the key will
|
|
be <literal>0</literal> (zero).
|
|
</para>
|
|
|
|
<para>
|
|
Note that the maximum integer key used for this <emphasis>need not
|
|
currently exist in the <type>array</type></emphasis>. It need only have
|
|
existed in the <type>array</type> at some time since the last time the
|
|
<type>array</type> was re-indexed. The following example illustrates:
|
|
</para>
|
|
|
|
<informalexample>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
// Create a simple array.
|
|
$array = array(1, 2, 3, 4, 5);
|
|
print_r($array);
|
|
|
|
// Now delete every item, but leave the array itself intact:
|
|
foreach ($array as $i => $value) {
|
|
unset($array[$i]);
|
|
}
|
|
print_r($array);
|
|
|
|
// Append an item (note that the new key is 5, instead of 0).
|
|
$array[] = 6;
|
|
print_r($array);
|
|
|
|
// Re-index:
|
|
$array = array_values($array);
|
|
$array[] = 7;
|
|
print_r($array);
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
&example.outputs;
|
|
<screen>
|
|
<![CDATA[
|
|
Array
|
|
(
|
|
[0] => 1
|
|
[1] => 2
|
|
[2] => 3
|
|
[3] => 4
|
|
[4] => 5
|
|
)
|
|
Array
|
|
(
|
|
)
|
|
Array
|
|
(
|
|
[5] => 6
|
|
)
|
|
Array
|
|
(
|
|
[0] => 6
|
|
[1] => 7
|
|
)
|
|
]]>
|
|
</screen>
|
|
</informalexample>
|
|
|
|
</note>
|
|
|
|
</sect3>
|
|
</sect2><!-- end syntax -->
|
|
|
|
<sect2 xml:id="language.types.array.useful-funcs">
|
|
<title>Useful functions</title>
|
|
|
|
<para>
|
|
There are quite a few useful functions for working with arrays. See the
|
|
<link linkend="ref.array">array functions</link> section.
|
|
</para>
|
|
|
|
<note>
|
|
<para>
|
|
The <function>unset</function> function allows removing keys from an
|
|
<type>array</type>. Be aware that the array will <emphasis>not</emphasis> be
|
|
reindexed. If a true "remove and shift" behavior is desired, the
|
|
<type>array</type> can be reindexed using the
|
|
<function>array_values</function> function.
|
|
</para>
|
|
|
|
<informalexample>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?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')
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</informalexample>
|
|
</note>
|
|
|
|
<para>
|
|
The &foreach; control
|
|
structure exists specifically for <type>array</type>s. It provides an easy
|
|
way to traverse an <type>array</type>.
|
|
</para>
|
|
</sect2>
|
|
|
|
<sect2 xml:id="language.types.array.donts">
|
|
<title>Array do's and don'ts</title>
|
|
|
|
<sect3 xml:id="language.types.array.foo-bar">
|
|
<title>Why is <literal>$foo[bar]</literal> wrong?</title>
|
|
|
|
<para>
|
|
Always use quotes around a string literal array index. For example,
|
|
<literal>$foo['bar']</literal> is correct, while
|
|
<literal>$foo[bar]</literal> is not. But why? It is common to encounter this
|
|
kind of syntax in old scripts:
|
|
</para>
|
|
|
|
<informalexample>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
$foo[bar] = 'enemy';
|
|
echo $foo[bar];
|
|
// etc
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</informalexample>
|
|
|
|
<para>
|
|
This is wrong, but it works. The reason is that this code has an undefined
|
|
constant (bar) rather than a <type>string</type> ('bar' - notice the
|
|
quotes). PHP may in the future define constants which, unfortunately for such
|
|
code, have the same name. It works because PHP automatically converts a
|
|
<emphasis>bare string</emphasis> (an unquoted <type>string</type> which does
|
|
not correspond to any known symbol) into a <type>string</type> which
|
|
contains the bare <type>string</type>. For instance, if there is no defined
|
|
constant named <constant>bar</constant>, then PHP will substitute in the
|
|
<type>string</type> <literal>'bar'</literal> and use that.
|
|
</para>
|
|
|
|
<note>
|
|
<simpara>
|
|
This does not mean to <emphasis>always</emphasis> quote the key. Do not
|
|
quote keys which are <link linkend="language.constants">constants</link> or
|
|
<link linkend="language.variables">variables</link>, as this will prevent
|
|
PHP from interpreting them.
|
|
</simpara>
|
|
|
|
<informalexample>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
error_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";
|
|
}
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</informalexample>
|
|
&example.outputs;
|
|
<screen>
|
|
<![CDATA[
|
|
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
|
|
]]>
|
|
</screen>
|
|
</note>
|
|
|
|
<para>
|
|
More examples to demonstrate this behaviour:
|
|
</para>
|
|
|
|
<informalexample>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
// Show all errors
|
|
error_reporting(E_ALL);
|
|
|
|
$arr = array('fruit' => 'apple', 'veggie' => 'carrot');
|
|
|
|
// Correct
|
|
print $arr['fruit']; // apple
|
|
print $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 now
|
|
print $arr['fruit']; // apple
|
|
print $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 here
|
|
print "Hello $arr[fruit]"; // Hello apple
|
|
|
|
// With one exception: braces surrounding arrays within strings allows constants
|
|
// to be interpreted
|
|
print "Hello {$arr[fruit]}"; // Hello carrot
|
|
print "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 well
|
|
print "Hello $arr['fruit']";
|
|
print "Hello $_GET['foo']";
|
|
|
|
// Concatenation is another option
|
|
print "Hello " . $arr['fruit']; // Hello apple
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</informalexample>
|
|
|
|
<para>
|
|
When <link linkend="ini.error-reporting">error_reporting</link> is set to
|
|
show <constant>E_NOTICE</constant> level errors (by setting it to
|
|
<constant>E_ALL</constant>, for example), such uses will become immediately
|
|
visible. By default,
|
|
<link linkend="ini.error-reporting">error_reporting</link> is set not to
|
|
show notices.
|
|
</para>
|
|
|
|
<para>
|
|
As stated in the <link linkend="language.types.array.syntax">syntax</link>
|
|
section, what's inside the square brackets ('<literal>[</literal>' and
|
|
'<literal>]</literal>') must be an expression. This means that code like
|
|
this works:
|
|
</para>
|
|
|
|
<informalexample>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
echo $arr[somefunc($bar)];
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</informalexample>
|
|
|
|
<para>
|
|
This is an example of using a function return value as the array index. PHP
|
|
also knows about constants:
|
|
</para>
|
|
|
|
<informalexample>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
$error_descriptions[E_ERROR] = "A fatal error has occurred";
|
|
$error_descriptions[E_WARNING] = "PHP issued a warning";
|
|
$error_descriptions[E_NOTICE] = "This is just an informal notice";
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</informalexample>
|
|
|
|
<para>
|
|
Note that <constant>E_ERROR</constant> is also a valid identifier, just like
|
|
<literal>bar</literal> in the first example. But the last example is in fact
|
|
the same as writing:
|
|
</para>
|
|
|
|
<informalexample>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
$error_descriptions[1] = "A fatal error has occurred";
|
|
$error_descriptions[2] = "PHP issued a warning";
|
|
$error_descriptions[8] = "This is just an informal notice";
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</informalexample>
|
|
|
|
<para>
|
|
because <constant>E_ERROR</constant> equals <literal>1</literal>, etc.
|
|
</para>
|
|
|
|
<sect4 xml:id="language.types.array.foo-bar.why">
|
|
<title>So why is it bad then?</title>
|
|
|
|
<para>
|
|
At some point in the future, the PHP team might want to add another
|
|
constant or keyword, or a constant in other code may interfere. For
|
|
example, it is already wrong to use the words <literal>empty</literal> and
|
|
<literal>default</literal> this way, since they are
|
|
<link linkend="reserved">reserved keywords</link>.
|
|
</para>
|
|
|
|
<note>
|
|
<simpara>
|
|
To reiterate, inside a double-quoted <type>string</type>, it's valid to
|
|
not surround array indexes with quotes so <literal>"$foo[bar]"</literal>
|
|
is valid. See the above examples for details on why as well as the section
|
|
on <link linkend="language.types.string.parsing">variable parsing in
|
|
strings</link>.
|
|
</simpara>
|
|
</note>
|
|
|
|
</sect4>
|
|
</sect3>
|
|
</sect2>
|
|
|
|
<sect2 xml:id="language.types.array.casting">
|
|
<title>Converting to array</title>
|
|
|
|
<para>
|
|
For any of the types: <type>integer</type>, <type>float</type>,
|
|
<type>string</type>, <type>boolean</type> and <type>resource</type>,
|
|
converting a value to an <type>array</type> results in an array with a single
|
|
element with index zero and the value of the scalar which was converted. In
|
|
other words, <literal>(array)$scalarValue</literal> is exactly the same as
|
|
<literal>array($scalarValue)</literal>.
|
|
</para>
|
|
|
|
<para>
|
|
If an <type>object</type> is converted to an <type>array</type>, the result
|
|
is an <type>array</type> whose elements are the <type>object</type>'s
|
|
properties. The keys are the member variable names, with a few notable
|
|
exceptions: integer properties are unaccessible;
|
|
private variables have the class name prepended to the variable
|
|
name; protected variables have a '*' prepended to the variable name. These
|
|
prepended values have null bytes on either side. This can result in some
|
|
unexpected behaviour:
|
|
</para>
|
|
|
|
<informalexample>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
|
|
class A {
|
|
private $A; // This will become '\0A\0A'
|
|
}
|
|
|
|
class B extends A {
|
|
private $A; // This will become '\0B\0A'
|
|
public $AA; // This will become 'AA'
|
|
}
|
|
|
|
var_dump((array) new B());
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</informalexample>
|
|
|
|
<para>
|
|
The above will appear to have two keys named 'AA', although one of them is
|
|
actually named '\0A\0A'.
|
|
</para>
|
|
|
|
<para>
|
|
Converting &null; to an <type>array</type> results in an empty
|
|
<type>array</type>.
|
|
</para>
|
|
</sect2>
|
|
|
|
<sect2 xml:id="language.types.array.comparing">
|
|
<title>Comparing</title>
|
|
|
|
<para>
|
|
It is possible to compare arrays with the <function>array_diff</function>
|
|
function and with
|
|
<link linkend="language.operators.array">array operators</link>.
|
|
</para>
|
|
</sect2>
|
|
|
|
<sect2 xml:id="language.types.array.examples">
|
|
<title>Examples</title>
|
|
|
|
<para>
|
|
The array type in PHP is very versatile. Here are some examples:
|
|
</para>
|
|
|
|
<informalexample>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
// This:
|
|
$a = array( 'color' => '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').
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</informalexample>
|
|
|
|
<example>
|
|
<title>Using array()</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
// Array as (property-)map
|
|
$map = array( 'version' => 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();
|
|
?>
|
|
]]>
|
|
<!-- TODO example of
|
|
- overwriting keys
|
|
- using vars/functions as key/values
|
|
- warning about references
|
|
-->
|
|
</programlisting>
|
|
</example>
|
|
|
|
<example xml:id="language.types.array.examples.loop">
|
|
<title>Collection</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
$colors = array('red', 'blue', 'green', 'yellow');
|
|
|
|
foreach ($colors as $color) {
|
|
echo "Do you like $color?\n";
|
|
}
|
|
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
&example.outputs;
|
|
<screen>
|
|
<![CDATA[
|
|
Do you like red?
|
|
Do you like blue?
|
|
Do you like green?
|
|
Do you like yellow?
|
|
]]>
|
|
</screen>
|
|
</example>
|
|
|
|
<para>
|
|
Changing the values of the <type>array</type> directly is possible since PHP
|
|
5 by passing them by reference. Before that, a workaround is necessary:
|
|
</para>
|
|
|
|
<example xml:id="language.types.array.examples.changeloop">
|
|
<title>Changing element in the loop</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
// PHP 5
|
|
foreach ($colors as &$color) {
|
|
$color = strtoupper($color);
|
|
}
|
|
unset($color); /* ensure that following writes to
|
|
$color will not modify the last array element */
|
|
|
|
// Workaround for older versions
|
|
foreach ($colors as $key => $color) {
|
|
$colors[$key] = strtoupper($color);
|
|
}
|
|
|
|
print_r($colors);
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
&example.outputs;
|
|
<screen>
|
|
<![CDATA[
|
|
Array
|
|
(
|
|
[0] => RED
|
|
[1] => BLUE
|
|
[2] => GREEN
|
|
[3] => YELLOW
|
|
)
|
|
]]>
|
|
</screen>
|
|
</example>
|
|
|
|
<para>
|
|
This example creates a one-based array.
|
|
</para>
|
|
|
|
<example>
|
|
<title>One-based index</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
$firstquarter = array(1 => 'January', 'February', 'March');
|
|
print_r($firstquarter);
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
&example.outputs;
|
|
<screen>
|
|
<![CDATA[
|
|
Array
|
|
(
|
|
[1] => 'January'
|
|
[2] => 'February'
|
|
[3] => 'March'
|
|
)
|
|
]]>
|
|
</screen>
|
|
</example>
|
|
|
|
<example>
|
|
<title>Filling an array</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
// fill an array with all items from a directory
|
|
$handle = opendir('.');
|
|
while (false !== ($file = readdir($handle))) {
|
|
$files[] = $file;
|
|
}
|
|
closedir($handle);
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</example>
|
|
|
|
<para>
|
|
<type>Array</type>s are ordered. The order can be changed using various
|
|
sorting functions. See the <link linkend="ref.array">array functions</link>
|
|
section for more information. The <function>count</function> function can be
|
|
used to count the number of items in an <type>array</type>.
|
|
</para>
|
|
|
|
<example>
|
|
<title>Sorting an array</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
sort($files);
|
|
print_r($files);
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</example>
|
|
|
|
<para>
|
|
Because the value of an <type>array</type> can be anything, it can also be
|
|
another <type>array</type>. This enables the creation of recursive and
|
|
multi-dimensional <type>array</type>s.
|
|
</para>
|
|
|
|
<example>
|
|
<title>Recursive and multi-dimensional arrays</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
$fruits = array ( "fruits" => 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 above
|
|
echo $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";
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</example>
|
|
|
|
<para>
|
|
<type>Array</type> assignment always involves value copying. Use the
|
|
<link linkend="language.operators">reference operator</link> to copy an
|
|
<type>array</type> by reference.
|
|
</para>
|
|
|
|
<informalexample>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
$arr1 = array(2, 3);
|
|
$arr2 = $arr1;
|
|
$arr2[] = 4; // $arr2 is changed,
|
|
// $arr1 is still array(2, 3)
|
|
|
|
$arr3 = &$arr1;
|
|
$arr3[] = 4; // now $arr1 and $arr3 are the same
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</informalexample>
|
|
|
|
</sect2>
|
|
</sect1>
|
|
|
|
<!-- Keep this comment at the end of the file
|
|
Local variables:
|
|
mode: sgml
|
|
sgml-omittag:t
|
|
sgml-shorttag:t
|
|
sgml-minimize-attributes:nil
|
|
sgml-always-quote-attributes:t
|
|
sgml-indent-step:1
|
|
sgml-indent-data:t
|
|
indent-tabs-mode:nil
|
|
sgml-parent-document:nil
|
|
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
|
|
sgml-exposed-tags:nil
|
|
sgml-local-catalogs:nil
|
|
sgml-local-ecat-files:nil
|
|
End:
|
|
vim600: syn=xml fen fdm=syntax fdl=2 si
|
|
vim: et tw=78 syn=sgml
|
|
vi: ts=1 sw=1
|
|
-->
|