15.04.2018 Views

programming-for-dummies

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

506<br />

Using Arrays<br />

Using Arrays<br />

PHP creates arrays that can hold any type of data and grow as large as you<br />

need them without having to define a size ahead of time. To create an array,<br />

define an array name, the data you want to store, and the index number<br />

where you want to store that item in the array like this:<br />

$arrayname[index] = data;<br />

So if you wanted to store the string “Hello” and the number 4.23 in the<br />

first and second elements of an array, you could do the following:<br />

$myarray[0] = “Hello”;<br />

$myarray[1] = 4.23;<br />

For greater flexibility in retrieving data, PHP lets you create associative<br />

arrays, which let you identify data by a unique string (called a key) rather<br />

than an arbitrary index number. Instead of assigning data to a specific index<br />

number, you assign data to a unique string, such as<br />

$arrayname[“key”] = data;<br />

If you wanted to assign the number 3.14 to the “pi” key, you’d do this:<br />

$myarray[“pi”] = 3.14;<br />

To retrieve data from an associative array, use the key value, such as<br />

$variable = $arrayname[“key”];<br />

So if you wanted to retrieve data stored under the key “pi”, you could do<br />

the following:<br />

$myarray[“pi”] = 3.14;<br />

$number2use = $myarray[“pi”];<br />

The first line stores the value 3.14 into the array and assigns it to the key<br />

“pi”. The second line yanks out the data, associated with the key “pi”, and<br />

stores that data into the $number2use variable.<br />

PHP includes a library of built-in array functions <strong>for</strong> manipulating arrays<br />

such as array_pop (which removes the last element from an array),<br />

array_push (which adds an element to the end of an array, and sort<br />

(which sorts arrays in ascending order).

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!