5. Returning Values
function hello() {
echo “Hello $who”;
if ($who == “World”) {
return;
}
echo “, how are you?”;
}
hello (“World”); //Displays “Hello World”
hello (“Reader”); //Displays “Hello Reader, how are you?”
6. Returning Values
function &query($sql)
{
$result = mysql_query($sql);
return $result;
}
//The following is incorrect and will
cause PHP to emit a notice when called.
function &getHello()
{
return “Hello World”;
}
//This will also cause the warning to be
issued when called
function &test()
{
echo „This is a test‟;
}
17. Printing Arrays
• PHP provides two functions that can be used to output a
variable’s value recursively
• print_r()
• var_dump().
18. Enumerative vs Associative
• Arrays can be roughly divided in two categories: enumerative and
associative.
• Enumerative arrays are indexed using only numerical indexes
• Associative arrays(sometimes referred to as dictionaries) allow the
association of an arbitrary key to every element.
19. Enumerative vs Associative, cont’d
When an element is added to an array without specifying a key, PHP
automatically assigns a numeric one that is equal to the greatest numeric key
already in existence in the array, plus one:
$a = array (2 => 5);
$a[] = ‟a‟; // This will have a key of 3
$a = array (‟4‟ => 5, ‟a‟ => ‟b‟);
$a[] = 44; // This will have a key of 5
20. Array keys are case-sensitive, but type insensitive. Thus, the key ’A’
is different from the key ’a’, but the keys ’1’ and 1 are the same.
However, the conversion is only applied if a string key contains
the traditional decimal representation of a number; thus, for
example, the key ’01’ is not the same as the key 1.
NOTE WELL
32. Array Iteration
• One of the most common operations you will perform with arrays
• PHP arrays require a set of functionality that matches their flexibility
• “normal” looping structures cannot cope with the fact that array keys do not
need to be continuous
$a = array (‟a‟ => 10, 10 => 20, ‟c‟ => 30);
38. Sorting Arrays
SORT_REGULAR
Compare items as they appear in the array, without performing any kind of
conversion. This is the default behaviour.
SORT_NUMERIC
Convert each element to a numeric value for sorting purposes.
SORT_STRING
Compare all elements as strings.
Functions are the heart of PHP programmingThe ability to encapsulate any piece of code that it can be called repeatedly is invaluable
Functions can also be declared that they return by referenceAllows the return of a variable instead of a copyOne caveat: a variable must be returned
Global: defined outside any function or class; accessible/available throughout lifecycle of programFunction: defined within a function; unavailable after function execution
To access global variables within a function two ways exist:“import” the variable using the global keywordusing the superglobal array
Some programmers prefer to use the $GLOBALS superglobal array, which contains all the variables in a global scope.
PHP provides three functions to handle variable-length argument lists:func_num_args()func_get_arg()func_get_args()
It’s nearly impossible to provide comprehensive test cases if a function that accepts a variable number of arguments isn’t constructed properly.
All arrays are ordered collections of item, called elementsPHP arrays are extremely flexible allowing numeric keys, auto-incremented keys, alpha-numeric keysCapable of storing practically any value, including other arraysOver 70 functions for array manipulation
Arrays are created one of two waysThe first line of code creates an array by only specifying the values of its three elements. Since every element of an array must also have a key, PHP automatically assigns a numeric key to each element, starting from zero. In the second example, the array keys are specified in the call to array()—in this case, three alphabetical keys (note that the length of the keys is arbitrary).In the third example, keys are assigned “out of order,” so that the first element of the array has, in fact, the key 5—note here the use of a “dangling comma” after the last element, which is perfectly legal from a syntactical perspective and has no effect on the final array. Finally, in the fourth example creates an empty array.
The second method of accessing arrays is by means of the array operator ([ ])
While both functions recursively print out the contents of composite value, only var_dump() outputs the data types of each valueOnly var_dump() is capable of outputting the value of more than one variable at the same timeOnly print_r can return its output as a string, as opposed to writing it to the script’s standard outputGenerally speaking, echo will cover most output requirements, while var_dump() and print_r() offer a more specialized set of functionality that works well as an aid in debugging.
In PHP, this distinction is significantly blurred, as you can create an enumerative array and then add associative elements to it (while still maintaining elements of an enumeration). What’s more, arrays behave more like ordered maps and can actually be used to simulate a number of different structures, including queues and stacks.
PHP provides a great amount of flexibility in how numeric keys can be assigned to arraysCan be any integer number (both negative and positive)Don’t need to be sequential, so that a large gap can exist between the indices of two consecutive values without the need to create intermediate values to cover everypossible key in between.
To create multi-dimensional arrays, simply assign an array as the value for an array element. With PHP, we can do this for one or more elements within any array—thus allowing for infinite levels of nesting.
It is sometimes simpler to work with the values of an array by assigning them to individual variables.While this can be accomplished by extracting individual elements and assigning each to a different variable, PHP provides a quick shortcut, the list() construct
The addition operator + can be used to create the union of its two operands
If the two arrays had common keys (either string or numeric), they would only appear once in the end result
Array-to-array comparison is a relatively rare occurrence, but it can be performed using another set of operators.The equivalence operator == returns true if both arrays have the same number of elements with the same values and keys, regardless of their order.The identity operator ===, on the other hand, returns true only if the array contains the same key/value pairs in the same order.
Inequality operator only ensures that both arrays contain the same elements with the same keys, whereas the non-identity operator also verifies their position.
The size of an array can be retrieved by calling the count() functioncount() cannot be used to determine whether a variable contains an array—since running it on a scalar value will return one. The right way to tell whether a variable contains an array is to use is_array() instead.
A similar problem exists with determining whether an element with the given key exists. This is often done by calling isset()However, isset() has the major drawback of considering an element whose value is NULL—which is perfectly valid—as inexistent:
The correct way to determine whether an array element exists is to use array_key_exists() in_array() function: determine whether an element with a given value exists in an array
An element can be deleted from an array by unsetting it
Two functions that have rather confusing names and that are sometimes misused: array_flip() and array_reverse()array_flip(): inverts the value of each element of an array with its keyarray_reverse(): inverts the order of the array’s elements, so that the last one appears first
We have created a function that will display all the values in an array. First, we call reset() to rewind the internal array pointer. Next, using a while loop, we display the current key and value, using the key() and current() functions. Finally, we advance the array pointer, using next(). The loop continues until we no longer have a valid key.
We have created a function that will display all the values in an array. First, we call reset() to rewind the internal array pointer. Next, using a while loop, we display the current key and value, using the key() and current() functions. Finally, we advance the array pointer, using next(). The loop continues until we no longer have a valid key.
The array_walk() function and its recursive cousin array_walk_recursive() can be used to perform an iteration of an array in which a user-defined function is called.One thing to note about array_walk_recursive() is that it will not call the user-defined function on anything but scalar values; because of this, the first set of keys, internal and custom, are never passed in.
total of 11 functions in the PHP core whose only goal is to provide various methods of sorting the contents of an arraysort() effectively destroys all the keys in the array and renumbers its elements starting from zero
If you wish to maintain key association, you can use asort() insteadBoth sort() and asort() sort values in ascending order. To sort them in descending order, you can use rsort() and arsort().
Both sort() and asort() accept a second, optional parameter that allows you to specify how the sort operation takes place
The sorting operation performed by sort() and asort() simply takes into consideration either the numeric value of each element, or performs a byte-by-byte comparison of strings values. This can result in an “unnatural” sorting order—for example, the string value ’10t’ will be considered “lower” than ’2t’ because it starts with the character 1, which has a lower value than 2. If this sorting algorithm doesn’t work well for your needs, you can try using natsort() insteadThe natsort() function will, unlike sort(), maintain all the key-value associations in the array.
The key-value association is lost; however, this problem is easily over-come by using another array function—array_keys()
Returns an array whose values are the keys of the array passed to it
Returns one or more random keys from an array
Arrays are often used as stacks (Last In, First Out, or LIFO) and queue (First In, First Out, or FIFO) structures. PHP simplifies this approach by providing a set of functions can be used to push and pop (for stacks) and shift and unshift (for queues) elements from an array.In this example, we first, create an array, and we then add two elements to it using array_push(). Next, using array_pop(), we extract the last element added to the array.
If you intend to use an array as a queue (FIFO), you can add elements at the be-ginning using array_unshift() and remove them again using array_shift()
Some PHP functions are designed to perform set operations on arrays. For example, array_diff() is used to compute the difference between two arraysThe call to array_diff() will cause all the values of $a that do not also appear in $b to be retained, while everything else is discardedConversely to array_diff(), array_intersect() will compute the intersection be-tween two arrays