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 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510
|
<?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>
<note>
<para>
A short array syntax exists which replaces
<literal>array()</literal> with <literal>[]</literal>.
</para>
</note>
<example>
<title>A simple array</title>
<programlisting role="php">
<![CDATA[
<?php
$array = array(
"foo" => "bar",
"bar" => "foo",
);
// Using the short array syntax
$array = [
"foo" => "bar",
"bar" => "foo",
];
?>
]]>
</programlisting>
</example>
<para>
The <replaceable>key</replaceable> can either be an <type>int</type>
or a <type>string</type>. The <replaceable>value</replaceable> can be
of any type.
</para>
<para xml:id="language.types.array.key-casts">
Additionally the following <replaceable>key</replaceable> casts will occur:
<itemizedlist>
<listitem>
<simpara>
<type>String</type>s containing valid decimal <type>int</type>s, unless the number is preceded by a <literal>+</literal> sign, will be cast to the
<type>int</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>int</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>int</type>s, too, i.e. the key
&true; will actually be stored under <literal>1</literal>
and the key &false; 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>int</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>int</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>int</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>
<example>
<title>Complex Type Casting and Overwriting example</title>
<para>
This example includes all variations of type casting of keys and overwriting
of elements.
</para>
<programlisting role="php">
<![CDATA[
<?php
$array = array(
1 => 'a',
'1' => 'b', // the value "a" will be overwritten by "b"
1.5 => 'c', // the value "b" will be overwritten by "c"
-1 => 'd',
'01' => 'e', // as this is not an integer string it will NOT override the key for 1
'1.5' => 'f', // as this is not an integer string it will NOT override the key for 1
true => 'g', // the value "c" will be overwritten by "g"
false => 'h',
'' => 'i',
null => 'j', // the value "i" will be overwritten by "j"
'k', // value "k" is assigned the key 2. This is because the largest integer key before that was 1
2 => 'l', // the value "k" will be overwritten by "l"
);
var_dump($array);
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
array(7) {
[1]=>
string(1) "g"
[-1]=>
string(1) "d"
["01"]=>
string(1) "e"
["1.5"]=>
string(1) "f"
[0]=>
string(1) "h"
[""]=>
string(1) "j"
[2]=>
string(1) "l"
}
]]>
</screen>
</example>
<example>
<title>Negative index example</title>
<simpara>
When assigning a negative integer key <literal>n</literal>, PHP will take care to
assign the next key to <literal>n+1</literal>.
</simpara>
<programlisting role="php">
<![CDATA[
<?php
$array = [];
$array[-5] = 1;
$array[] = 2;
var_dump($array);
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
array(2) {
[-5]=>
int(1)
[-4]=>
int(2)
}
]]>
</screen>
<warning>
<simpara>
Prior to PHP 8.3.0, assigning a negative integer key <literal>n</literal> would
assign the next key to <literal>0</literal>, the previous example would
therefore output:
</simpara>
<informalexample>
<screen>
<![CDATA[
array(2) {
[-5]=>
int(1)
[0]=>
int(2)
}
]]>
</screen>
</informalexample>
</warning>
</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>
Prior to PHP 8.0.0, square brackets and curly braces could be used interchangeably
for accessing array elements (e.g. <literal>$array[42]</literal> and <literal>$array{42}</literal>
would both do the same thing in the example above).
The curly brace syntax was deprecated as of PHP 7.4.0 and no longer supported as of PHP 8.0.0.
</para>
</note>
<example>
<title>Array dereferencing</title>
<programlisting role="php">
<![CDATA[
<?php
function getArray() {
return array(1, 2, 3);
}
$secondElement = getArray()[1];
?>
]]>
</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_WARNING</constant>-level error message
(<constant>E_NOTICE</constant>-level prior to PHP 8.0.0) will be
issued, and the result will be &null;.
</para>
</note>
<note>
<para>
Array dereferencing a scalar value which is not a <type>string</type>
yields &null;. Prior to PHP 7.4.0, that did not issue an error message.
As of PHP 7.4.0, this issues <constant>E_NOTICE</constant>;
as of PHP 8.0.0, this issues <constant>E_WARNING</constant>.
</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>int</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 or is set to &null; or &false;, 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 a variable by a direct
assignment.
</para>
<note>
<simpara>
As of PHP 7.1.0, applying the empty index operator on a string throws a fatal
error. Formerly, the string was silently converted to an array.
</simpara>
</note>
<note>
<simpara>
As of PHP 8.1.0, creating a new array from &false; value is deprecated.
Creating a new array from &null; and undefined values is still allowed.
</simpara>
</note>
<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>int</type> indices is taken, and the new key will be that maximum
value plus 1 (but at least 0). If no <type>int</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>
<sect3 xml:id="language.types.array.syntax.destructuring">
<title>Array destructuring</title>
<para>
Arrays can be destructured using the <literal>[]</literal> (as of PHP 7.1.0) or
<function>list</function> language constructs. These
constructs can be used to destructure an array into distinct variables.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$source_array = ['foo', 'bar', 'baz'];
[$foo, $bar, $baz] = $source_array;
echo $foo; // prints "foo"
echo $bar; // prints "bar"
echo $baz; // prints "baz"
?>
]]>
</programlisting>
</informalexample>
<para>
Array destructuring can be used in &foreach; to destructure
a multi-dimensional array while iterating over it.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$source_array = [
[1, 'John'],
[2, 'Jane'],
];
foreach ($source_array as [$id, $name]) {
// logic here with $id and $name
}
?>
]]>
</programlisting>
</informalexample>
<para>
Array elements will be ignored if the variable is not provided. Array
destructuring always starts at index <literal>0</literal>.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$source_array = ['foo', 'bar', 'baz'];
// Assign the element at index 2 to the variable $baz
[, , $baz] = $source_array;
echo $baz; // prints "baz"
?>
]]>
</programlisting>
</informalexample>
<para>
As of PHP 7.1.0, associative arrays can be destructured too. This also
allows for easier selection of the right element in numerically indexed
arrays as the index can be explicitly specified.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$source_array = ['foo' => 1, 'bar' => 2, 'baz' => 3];
// Assign the element at index 'baz' to the variable $three
['baz' => $three] = $source_array;
echo $three; // prints 3
$source_array = ['foo', 'bar', 'baz'];
// Assign the element at index 2 to the variable $baz
[2 => $baz] = $source_array;
echo $baz; // prints "baz"
?>
]]>
</programlisting>
</informalexample>
<para>
Array destructuring can be used for easy swapping of two variables.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$a = 1;
$b = 2;
[$b, $a] = [$a, $b];
echo $a; // prints 2
echo $b; // prints 1
?>
]]>
</programlisting>
</informalexample>
<note>
<para>
The spread operator (<literal>...</literal>) is not supported in assignments.
</para>
</note>
<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_WARNING</constant>-level error message
(<constant>E_NOTICE</constant>-level prior to PHP 8.0.0) will be
issued, and the result will be &null;.
</para>
</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 (<literal>bar</literal>) rather than a <type>string</type> (<literal>'bar'</literal> - notice the
quotes). 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>
<warning>
<simpara>
The fallback to treat an undefined constant as bare string issues an error
of level <constant>E_NOTICE</constant>.
This has been deprecated as of PHP 7.2.0, and issues an error
of level <constant>E_WARNING</constant>.
As of PHP 8.0.0, it has been removed and throws an
<classname>Error</classname> exception.
</simpara>
</warning>
<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>int</type>, <type>float</type>,
<type>string</type>, <type>bool</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, <code>(array) $scalarValue</code> 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 <literal>NUL</literal> bytes on either side.
Uninitialized <link linkend="language.oop5.properties.typed-properties">typed properties</link>
are silently discarded.
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
class A {
private $B;
protected $C;
public $D;
function __construct()
{
$this->{1} = null;
}
}
var_export((array) new A());
?>
]]>
</programlisting>
&example.outputs;
<screen>
<![CDATA[
array (
'' . "\0" . 'A' . "\0" . 'B' => NULL,
'' . "\0" . '*' . "\0" . 'C' => NULL,
'D' => NULL,
1 => NULL,
)
]]>
</screen>
</informalexample>
<para>
These <literal>NUL</literal> 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>
&example.outputs;
<screen>
<![CDATA[
array(3) {
["BA"]=>
NULL
["AA"]=>
NULL
["AA"]=>
NULL
}
]]>
</screen>
</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.unpacking">
<title>Array unpacking</title>
<para>
An array prefixed by <code>...</code> will be expanded in place during array definition.
Only arrays and objects which implement <interfacename>Traversable</interfacename> can be expanded.
Array unpacking with <code>...</code> is available as of PHP 7.4.0.
</para>
<para>
It's possible to expand multiple times, and add normal elements before or after the <code>...</code> operator:
<example>
<title>Simple array unpacking</title>
<programlisting role="php">
<![CDATA[
<?php
// Using short array syntax.
// Also, works with array() syntax.
$arr1 = [1, 2, 3];
$arr2 = [...$arr1]; //[1, 2, 3]
$arr3 = [0, ...$arr1]; //[0, 1, 2, 3]
$arr4 = [...$arr1, ...$arr2, 111]; //[1, 2, 3, 1, 2, 3, 111]
$arr5 = [...$arr1, ...$arr1]; //[1, 2, 3, 1, 2, 3]
function getArr() {
return ['a', 'b'];
}
$arr6 = [...getArr(), 'c' => 'd']; //['a', 'b', 'c' => 'd']
?>
]]>
</programlisting>
</example>
</para>
<para>
Unpacking an array with the <code>...</code> operator follows the semantics of the <function>array_merge</function> function.
That is, later string keys overwrite earlier ones and integer keys are renumbered:
<example>
<title>Array unpacking with duplicate key</title>
<programlisting role="php">
<![CDATA[
<?php
// string key
$arr1 = ["a" => 1];
$arr2 = ["a" => 2];
$arr3 = ["a" => 0, ...$arr1, ...$arr2];
var_dump($arr3); // ["a" => 2]
// integer key
$arr4 = [1, 2, 3];
$arr5 = [4, 5, 6];
$arr6 = [...$arr4, ...$arr5];
var_dump($arr6); // [1, 2, 3, 4, 5, 6]
// Which is [0 => 1, 1 => 2, 2 => 3, 3 => 4, 4 => 5, 5 => 6]
// where the original integer keys have not been retained.
?>
]]>
</programlisting>
</example>
</para>
<note>
<para>
Keys that are neither integers nor strings throw a <classname>TypeError</classname>.
Such keys can only be generated by a <interfacename>Traversable</interfacename> object.
</para>
</note>
<note>
<para>
Prior to PHP 8.1, unpacking an array which has a string key is not supported:
</para>
<informalexample>
<programlisting role="php">
<![CDATA[
<?php
$arr1 = [1, 2, 3];
$arr2 = ['a' => 4];
$arr3 = [...$arr1, ...$arr2];
// Fatal error: Uncaught Error: Cannot unpack array with string keys in example.php:5
$arr4 = [1, 2, 3];
$arr5 = [4, 5];
$arr6 = [...$arr4, ...$arr5]; // works. [1, 2, 3, 4, 5]
?>
]]>
</programlisting>
</informalexample>
</note>
</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
by passing them by reference.
</para>
<example xml:id="language.types.array.examples.changeloop">
<title>Changing element in the loop</title>
<programlisting role="php">
<![CDATA[
<?php
foreach ($colors as &$color) {
$color = mb_strtoupper($color);
}
unset($color); /* ensure that following writes to
$color will not modify the last array element */
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
-->
|