Arrays

Syntax

Creating / modifying with square-bracket syntax




If $arr doesn't exist yet, it will be created. So this is also an alternative way to specify an array. To change a certain value, just assign a new value to an element specified with its key. If you want to remove a key/value pair, you need to unset() it.

Useful functions

Array do' s and don 'ts

Why is $foo[ bar ] wrong ?

This is wrong, but it works. Then, why is it wrong? The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes), and PHP may in future define constants which, unfortunately for your code, have the same name. It works, because the undefined constant gets converted to a string of the same name automatically for backward compatibility reasons.



This is an example of using a function return value as the array index. PHP also knows about constants, as you may have seen the E_* ones before. Note that E_ERROR is also a valid identifier, just like bar in the first example. But the last example is in fact the same as writing: because E_ERROR equals 1 , etc.

Converting to array

Examples



Exempel 7-4 .




Exempel 7-5 .




















Exempel 7-6 .










Exempel 7-7 .










Exempel 7-8 .




Exempel 7-9 .




Exempel 7-10 .