Chapter 6 PHP Arrays
array keyword
A more compact and faster assignment method uses the array keyword. Example 6-5 shows both a numeric and an associative array assigned using this method.
count
Although the each function and foreach...as loop structure are excellent ways to walk through an array's contents, sometimes you need to know exactly how many elements there are in your array, particularly if you will be referencing them directly. To count all the elements in the top level of an array, use a command such as this: echo count($fred); Should you wish to know how many elements there are altogether in a multidimensional array, you can use a statement such as the following: echo count($fred, 1); The second parameter is optional and sets the mode to use. It should be either 0 to limit counting to only the top level, or 1 to force recursive counting of all subarray elements too.
Associative array
An associative array is a type of array used in programming where each element is paired with a key, which is a unique identifier. Unlike numerically indexed arrays, where the keys are numerical and automatically assigned based on the element's position in the array, associative arrays allow the programmer to assign meaningful keys to values. These keys are typically strings, allowing for more readable and intuitive code. In place of a number (which doesn't convey any useful information, aside from the position of the item in the array), each item now has a unique name that you can use to reference it elsewhere, as with the echo statement—which simply prints out Laser Printer. The names (copier, inkjet, and so on) are called indexes or keys, and the items assigned to them (such as Laser Printer) are called values.
end array function
As with reset, you can move PHP's internal array pointer to the final element in an array using the end function, which also returns the value of the element, and can be used as in these examples: end($fred); $item = end($fred);
Compact function
At times you may want to use compact, the inverse of extract, to create an array from variables and their values. Example 6-14 shows how you might use this function. At times you may want to use compact, the inverse of extract, to create an array from variables and their values. Example 6-14 shows how you might use this function. php $fname = "Doctor"; $sname = "Who"; $planet = "Gallifrey"; $system = "Gridlock"; $constellation = "Kasterborous"; $contact = compact('fname', 'sname', 'planet', 'system', 'constellation'); print_r($contact); ?> Result Array ( [fname] => Doctor [sname] => Who [planet] => Gallifrey [system] => Gridlock [constellation] => Kasterborous ) Note how compact requires the variable names to be supplied in quotes, not preceded by a $ symbol. This is because compact is looking for a list of variable names, not their values.
is_array
Finds whether a variable is an array Arrays and variables share the same namespace. This means that you cannot have a string variable called $fred and an array also called $fred. If you're in doubt and your code needs to check whether a variable is an array, you can use the is_array function, like this: Ex: Note that if $fred has not yet been assigned a value, an Undefined variable message will be generated.
Example of associative array
Here are some key characteristics of associative arrays: Key-Value Pairs: Each value stored in an associative array is associated with a unique key. The key is used to access the corresponding value. Flexibility in Keys: The keys in associative arrays can be strings or other types, depending on the programming language. This allows for more descriptive and flexible data structures. Order Not Guaranteed: While some languages maintain the order in which key-value pairs are inserted, associative arrays, in general, do not guarantee any specific order of elements. Direct Access: Values in associative arrays are accessed directly by their keys rather than by their position in the array. Usage: Associative arrays are especially useful when the data has an inherent structure that can be captured by key-value pairs, making it easier to read and manage. For example, storing the properties of an object, like the attributes of a user (name, email, age, etc.).
multidimensional array
In PHP, a multidimensional array is an array that contains one or more arrays within it. These arrays can hold any type of value, and the depth of nesting can vary. Essentially, a multidimensional array is an array of arrays. Basic Concept Single-dimensional array: An array with a single level of key-value pairs. Multidimensional array: An array where each element can itself be an array. This allows for the creation of complex data structures. Types of Multidimensional Arrays Two-dimensional arrays: These are the simplest form of multidimensional arrays. Think of it as an array of arrays, or a table with rows and columns. Three-dimensional arrays: An array of two-dimensional arrays. It's like a stack of tables or a cube. N-dimensional arrays: You can extend this concept to any number of dimensions, although beyond three dimensions, it becomes harder to visualize and manage.
Extract function
In PHP, the extract() function is used to import variables from an array into the current symbol table. This means it takes key-value pairs from an associative array and converts each key into a variable name with its corresponding value as the variable's value.
reset array function
In PHP, the reset() function is used to reset the internal pointer of an array to its first element. This function is particularly useful when you're dealing with array pointers, especially after you've iterated through an array using functions like next(), prev(), end(), etc., and you want to start over from the beginning of the array. Syntax: The syntax of the reset() function is quite straightforward: reset(array). array: The array whose pointer you want to reset. Return Value: The function returns the value of the first array element, or FALSE if the array is empty. $arr = ["apple", "banana", "cherry"]; end($arr); // move the internal pointer to the last element of the array echo current($arr); // Outputs: cherry reset($arr); // reset the pointer to the first element echo current($arr); // Outputs: apple In this example, after using end() to move the pointer to the last element and current() to display it, reset() is used to bring the pointer back to the beginning of the array. Purpose: reset() is often used in loops where the array pointer is being manipulated, and you need to start the iteration from the beginning again. It's also useful to ensure that the array pointer is at the beginning if you're using a function that relies on the internal pointer's position, like current() or each(). Considerations: Remember that reset() affects the internal pointer of the array, which is used by other PHP array functions. Using reset() is only relevant when dealing with functions that depend on the internal array pointer.
Explode Function
explode is a very useful function with which you can take a string containing several items separated by a single character (or string of characters) and then place each of these items into an array. One handy example is to split up a sentence into an array containing all its words, as in Example 6-12.
recursive
relating to or involving a program or routine of which a part requires the application of the whole, so that its explicit interpretation requires in general many successive executions.
Numerically Indexed Arrays
Numerically indexed arrays, also commonly referred to as numeric arrays or indexed arrays, are collections of data where each element is assigned a unique numeric index which denotes its position within the array. The indexing typically starts at 0, meaning the first element of the array has an index of 0, the second an index of 1, and so on. Here are some key points about numerically indexed arrays: Ordering: The numeric indices determine the order of the elements within the array. This makes it easy to iterate over the array using a loop that runs from 0 to one less than the length of the array. Access: You can access any element of a numeric array directly if you know its index. For example, array[0] will give you the first element. Efficiency: Numeric indices allow for efficient storage and access because the positional index corresponds directly to an offset in memory where the data is stored.
Example of for each loop with Associative array
Remember that associative arrays do not require numeric indexes, so the variable $j is not used in this example. Instead, each item of the array $paper is fed into the key/value pair of variables $item and $description, from which they are printed out. The displayed result of this code is as follows: copier: Copier & Multipurpose inkjet: Inkjet Printer laser: Laser Printer photo: Photographic Paper
sort function
Sorting is so common that PHP provides a built-in function for it. In its simplest form, you would use it like this: sort($fred); Unlike some other functions, sort will act directly on the supplied array rather than returning a new array of sorted elements. It returns TRUE on success and FALSE on error and also supports a few flags—the main two that you might wish to use force items to be sorted either numerically or as strings, like this: sort($fred, SORT_NUMERIC); sort($fred, SORT_STRING);
<pre>
The <pre> tag is not specific to PHP; it's actually an HTML tag. The <pre> tag is used to define preformatted text. The content inside a <pre> element is displayed in a fixed-width font (usually Courier), and it preserves both spaces and line breaks. This tag is particularly useful when you want to display code or text content where the spacing and formatting are important. In the context of PHP, the <pre> tag is often used when echoing or printing content to the browser to maintain the formatting of the data, especially when displaying arrays or objects for debugging purposes. It makes the output more readable, as it maintains the formatting you have in your PHP code. In this example, the <pre> tag is used to wrap the output of print_r($array). Without the <pre> tags, the browser would display the array in a continuous line, ignoring the line breaks and spaces. With the <pre> tags, the browser preserves the format as it is shown in the source code, making it much easier to read and understand the structure of the array. It's important to note that <pre> is purely for display purposes in HTML and has no functional effect in PHP itself. It's only relevant when PHP is used to generate HTML content for web pages.
for each as loop
The creators of PHP have gone to great lengths to make the language easy to use. So, not content with the loop structures already provided, they added another one especially for arrays: the foreach...as loop. Using it, you can step through all the items in an array, one at a time, and do something with them. The process starts with the first item and ends with the last one, so you don't even have to know how many items there are in an array. Example 6-6 shows how foreach...as can be used to rewrite Example 6-3. When PHP encounters a foreach statement, it takes the first item of the array and places it in the variable following the as keyword; and each time control flow returns to the foreach, the next array element is placed in the as keyword. In this case, the variable $item is set to each of the four values in turn in the array $paper. Once all values have been used, execution of the loop ends. The output from this code is exactly the same as in Example 6-3.
shuffle function
There may be times when you need the elements of an array to be put in random order, such as when you're creating a game of playing cards: shuffle($cards); Like sort, shuffle acts directly on the supplied array and returns TRUE on success or FALSE on error.
You can directly access a particular element of the array by using square brackets:
This outputs the value Adhesives.
Example of a multidimensional array
To make things clearer now that the code is starting to grow, I've renamed some of the elements. For example, because the previous array $paper is now just a subsection of a larger array, the main array is now called $products. Within this array, there are three items—paper, pens, and misc—each of which contains another array with key/value pairs. If necessary, these subarrays could have contained even further arrays. For example, under ball there might be many different types and colors of ballpoint pens available in the online store. But for now, I've restricted the code to a depth of just two. Once the array data has been assigned, I use a pair of nested foreach...as loops to print out the various values. The outer loop extracts the main sections from the top level of the array, and the inner loop extracts the key/value pairs for the categories within each section. As long as you remember that each level of the array works the same way (it's a key/value pair), you can easily write code to access any element at any level. The echo statement makes use of the PHP escape character \t, which outputs a tab. Although tabs are not normally significant to the web browser, I let them be used for layout by using the <pre>...</pre> tags, which tell the web browser to format the text as preformatted and monospaced, and not to ignore whitespace characters such as tabs and line feeds. The output from this code looks like the following: paper: copier (Copier & Multipurpose) paper: inkjet (Inkjet Printer) paper: laser (Laser Printer) paper: photo (Photographic Paper) pens: ball (Ball Point) pens: hilite (Highlighters) pens: marker (Markers) misc: tape (Sticky Tape) misc: glue (Adhesives) misc: clips (Paperclips)
