Ubuntu Unleashed 2019 Edition: Covering 18.04, 18.10, 19.04

(singke) #1

1 , 2 , 3 , and 4. Because no keys are specified, PHP automatically assigns
keys for us, starting at 0 and counting upward—giving keys 0 , 1 , 2 , and 3.
Then we add a new element with the [] operator, specifying 4 as the key and
“Hello” as the value. Next, [] is used again to add an element with the
value “World!” and no key and then again to add an element with the key
“elephant” and the value “wombat”. The line after that demonstrates
using a string key with an array value—an array inside an array (a
multidimensional array).


The next three lines demonstrate reading back from an array, first using a
numerical key, then using a string key, and then using a string key and a
numerical key. Remember that the “foo” element is an array in itself, so that
third reading line retrieves the array and then prints the second element
(arrays start at 0 , remember). The last line blanks the array by simply using
array() with no parameters, which creates an array with elements and
assigns it to $myarr.


The following is an alternative way of using array() that allows you to
specify keys along with their values:


Click here to view code image
$myarr = array("key1" => "value1", "key2" => "value2",
7 => "foo", 15 => "bar");


Which method you choose really depends on whether you want specific keys
or want PHP to pick them for you.


Constants


Constants are frequently used in functions that require specific values to be
passed in. For example, a popular function is extract(), which takes all
the values in an array and places them into variables in their own right. You
can choose to change the name of the variables as they are extracted by using
the second parameter; send it 0 , and it overwrites variables with the same
names as those being extracted; send it 1 , and it skips variables with the same
names; send it 5 , and it prefixes variables only if they exist already; and so
on. Of course, no one wants to have to remember a lot of numbers for each
function, so you can instead use EXTR_OVERWRITE for 0 , EXTR_SKIP for
1 , EXTR_PREFIX_IF_EXISTS for 5 , and so on, which is much easier.


You can create constants of your own by using the define() function.
Unlike variables, constants do not start with a dollar sign. Code to define a
constant looks like this:

Free download pdf