1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122
|
<?xml version="1.0" encoding="utf-8"?>
<!-- $Revision: 332515 $ -->
<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
-->
|