= PHP_4_2_0, PHP_5, PHP_7, PHP_8 // array_chunk() - PHP_4 >= PHP_4_2_0, PHP_5, PHP_7, PHP_8 // OFFLINE | array_column() - PHP_5 >= PHP_5_5_0, PHP_7, PHP_8 // OFFLINE | array_combine() - PHP_5, PHP_7, PHP_8 // array_count_values() - PHP_4, PHP_5, PHP_7, PHP_8 // array_diff_assoc() - PHP_4 >= PHP_4_3_0, PHP_5, PHP_7, PHP_8 // OFFLINE | array_diff_key() - PHP_5 >= PHP_5_1_0, PHP_7, PHP_8 // OFFLINE | array_diff_uassoc() - PHP_5, PHP_7, PHP_8 // OFFLINE | array_diff_ukey() - PHP_5 >= PHP_5_1_0, PHP_7, PHP_8 // array_diff() - PHP_4 >= PHP_4_0_1, PHP_5, PHP_7, PHP_8 // OFFLINE | array_fill_keys() - PHP_5 >= PHP_5_2_0, PHP_7, PHP_8 // array_fill() - PHP_4 >= PHP_4_2_0, PHP_5, PHP_7, PHP_8 // array_filter() - PHP_4 >= PHP_4_0_6, PHP_5, PHP_7, PHP_8 // array_flip() - PHP_4, PHP_5, PHP_7, PHP_8 // array_intersect_assoc() - PHP_4 >= PHP_4_3_0, PHP_5, PHP_7, PHP_8 // OFFLINE | array_intersect_key() - PHP_5 >= PHP_5_1_0, PHP_7, PHP_8 // OFFLINE | array_intersect_uassoc() - PHP_5, PHP_7, PHP_8 // OFFLINE | array_intersect_ukey() - PHP_5 >= PHP_5_1_0, PHP_7, PHP_8 // array_intersect() - PHP_4 >= PHP_4_0_1, PHP_5, PHP_7, PHP_8 // OFFLINE | array_is_list() - PHP_8 >= PHP_8_1_0 // array_key_exists() - PHP_4 >= PHP_4_0_7, PHP_5, PHP_7, PHP_8 // OFFLINE | array_key_first() - PHP_7 >= PHP_7_3_0, PHP_8 // OFFLINE | array_key_last() - PHP_7 >= PHP_7_3_0, PHP_8 // array_keys() - PHP_4, PHP_5, PHP_7, PHP_8 // array_map() - PHP_4 >= PHP_4_0_6, PHP_5, PHP_7, PHP_8 // array_merge_recursive() - PHP_4 >= PHP_4_0_1, PHP_5, PHP_7, PHP_8 // array_merge() - PHP_4, PHP_5, PHP_7, PHP_8 // array_multisort() - PHP_4, PHP_5, PHP_7, PHP_8 // array_pad() - PHP_4, PHP_5, PHP_7, PHP_8 // array_pop() - PHP_4, PHP_5, PHP_7, PHP_8 // OFFLINE | array_product() - PHP_5 >= PHP_5_1_0, PHP_7, PHP_8 // array_push() - PHP_4, PHP_5, PHP_7, PHP_8 // array_rand() - PHP_4, PHP_5, PHP_7, PHP_8 // array_reduce() - PHP_4 >= PHP_4_0_5, PHP_5, PHP_7, PHP_8 // OFFLINE | array_replace_recursive() - PHP_5 >= PHP_5_3_0, PHP_7, PHP_8 // OFFLINE | array_replace() - PHP_5 >= PHP_5_3_0, PHP_7, PHP_8 // array_reverse() - PHP_4, PHP_5, PHP_7, PHP_8 // array_search() - PHP_4 >= PHP_4_0_5, PHP_5, PHP_7, PHP_8 // array_shift() - PHP_4, PHP_5, PHP_7, PHP_8 // array_slice() - PHP_4, PHP_5, PHP_7, PHP_8 // array_splice() - PHP_4, PHP_5, PHP_7, PHP_8 // array_sum() - PHP_4 >= PHP_4_0_4, PHP_5, PHP_7, PHP_8 // OFFLINE | array_udiff_assoc() - PHP_5, PHP_7, PHP_8 // OFFLINE | array_udiff_uassoc() - PHP_5, PHP_7, PHP_8 // OFFLINE | array_udiff() - PHP_5, PHP_7, PHP_8 // OFFLINE | array_uintersect_assoc() - PHP_5, PHP_7, PHP_8 // OFFLINE | array_uintersect_uassoc() - PHP_5, PHP_7, PHP_8 // OFFLINE | array_uintersect() - PHP_5, PHP_7, PHP_8 // array_unique() - PHP_4 >= PHP_4_0_1, PHP_5, PHP_7, PHP_8 // array_unshift() - PHP_4, PHP_5, PHP_7, PHP_8 // array_values() - PHP_4, PHP_5, PHP_7, PHP_8 // OFFLINE | array_walk_recursive() - PHP_5, PHP_7, PHP_8 // array_walk() - PHP_4, PHP_5, PHP_7, PHP_8 // array() - PHP_4, PHP_5, PHP_7, PHP_8 // arsort() - PHP_4, PHP_5, PHP_7, PHP_8 // asort() - PHP_4, PHP_5, PHP_7, PHP_8 // compact() - PHP_4, PHP_5, PHP_7, PHP_8 // count() - PHP_4, PHP_5, PHP_7, PHP_8 // current() - PHP_4, PHP_5, PHP_7, PHP_8 // OFFLINE | each() - PHP_4, PHP_5, PHP_7 // end() - PHP_4, PHP_5, PHP_7, PHP_8 // extract() - PHP_4, PHP_5, PHP_7, PHP_8 // in_array() - PHP_4, PHP_5, PHP_7, PHP_8 // key_exists() - PHP_4 >= PHP_4_0_6, PHP_5, PHP_7, PHP_8 // key() - PHP_4, PHP_5, PHP_7, PHP_8 // krsort() - PHP_4, PHP_5, PHP_7, PHP_8 // ksort() - PHP_4, PHP_5, PHP_7, PHP_8 // OFFLINE | list() - PHP_4, PHP_5, PHP_7, PHP_8 // natcasesort() - PHP_4, PHP_5, PHP_7, PHP_8 // natsort() - PHP_4, PHP_5, PHP_7, PHP_8 // next() - PHP_4, PHP_5, PHP_7, PHP_8 // pos() - PHP_4, PHP_5, PHP_7, PHP_8 // prev() - PHP_4, PHP_5, PHP_7, PHP_8 // range() - PHP_4, PHP_5, PHP_7, PHP_8 // reset() - PHP_4, PHP_5, PHP_7, PHP_8 // rsort() - PHP_4, PHP_5, PHP_7, PHP_8 // shuffle() - PHP_4, PHP_5, PHP_7, PHP_8 // sizeof() - PHP_4, PHP_5, PHP_7, PHP_8 // sort() - PHP_4, PHP_5, PHP_7, PHP_8 // uasort() - PHP_4, PHP_5, PHP_7, PHP_8 // uksort() - PHP_4, PHP_5, PHP_7, PHP_8 // usort() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== USING CLASSES (0) // ============================== USING DATA_TYPES (11) // array // int // bool // string // null // callable // mixed // float // false // object // Countable // ============================== END // REQUIREMENTS // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY // ============================== ABOUT // PHP Manual / Function Reference / Variable and Type Related Extensions / Arrays // URL: https://www.php.net/manual/en/book.array.php // ============================== DESCRIPTION // ARRAYS // LANGUAGE_REFERENCE_TYPES_ARRAYS // // ARRAYS - BEGIN // Arrays // // INTRODUCTION // INSTALLING_CONFIGURING // PREDEFINED_CONSTANTS // SORTING_ARRAYS // ARRAY_FUNCTIONS // // INTRODUCTION - BEGIN // Introduction // // These functions allow you to interact with and manipulate arrays in various ways. Arrays are essential for storing, managing, and operating on sets of variables. // Simple and multi-dimensional arrays are supported, and may be either user created or created by another function. There are specific database handling functions for populating arrays from database queries, and several functions return arrays. // Please see the Arrays section of the manual for a detailed explanation of how arrays are implemented and used in PHP. See also Array operators for other ways how to manipulate the arrays. // // LITERATURE_SOURCES // * PHP_NET (2023-09-15) // URL: https://www.php.net/manual/en/intro.array.php // INTRODUCTION - END // // INSTALLING_CONFIGURING - BEGIN // Installing/Configuring // // REQUIREMENTS // INSTALLATION // RUNTIME_CONFIGURATION // RESOURCE_TYPES // // REQUIREMENTS - BEGIN // Requirements // // No external libraries are needed to build this extension. // // LITERATURE_SOURCES // * PHP_NET (2023-09-15) // URL: https://www.php.net/manual/en/array.requirements.php // REQUIREMENTS - END // // INSTALLATION - BEGIN // Installation // // There is no installation needed to use these functions; they are part of the PHP core. // // LITERATURE_SOURCES // * PHP_NET (2023-09-15) // URL: https://www.php.net/manual/en/array.installation.php // INSTALLATION - END // // RUNTIME_CONFIGURATION - BEGIN // Runtime Configuration // // This extension has no configuration directives defined in php.ini. // // LITERATURE_SOURCES // * PHP_NET (2023-09-15) // URL: https://www.php.net/manual/en/array.configuration.php // RUNTIME_CONFIGURATION - END // // RESOURCE_TYPES - BEGIN // Resource Types // // This extension has no resource types defined. // // LITERATURE_SOURCES // * PHP_NET (2023-09-15) // URL: https://www.php.net/manual/en/array.resources.php // RESOURCE_TYPES - END // // LITERATURE_SOURCES // * PHP_NET (2023-09-15) // URL: https://www.php.net/manual/en/array.setup.php // INSTALLING_CONFIGURING - END // // PREDEFINED_CONSTANTS - BEGIN // Predefined Constants // // The constants below are always available as part of the PHP core. // // CASE_LOWER (int) - CASE_LOWER is used with array_change_key_case() and is used to convert array keys to lower case. This is also the default case for array_change_key_case(). As of PHP 8.2.0, only ASCII characters will be converted. // CASE_UPPER (int) - CASE_UPPER is used with array_change_key_case() and is used to convert array keys to upper case. As of PHP 8.2.0, only ASCII characters will be converted. // Sorting order flags: // SORT_ASC (int) - SORT_ASC is used with array_multisort() to sort in ascending order. // SORT_DESC (int) - SORT_DESC is used with array_multisort() to sort in descending order. // Sorting type flags: used by various sort functions // SORT_REGULAR (int) - SORT_REGULAR is used to compare items normally. // SORT_NUMERIC (int) - SORT_NUMERIC is used to compare items numerically. // SORT_STRING (int) - SORT_STRING is used to compare items as strings. // SORT_LOCALE_STRING (int) - SORT_LOCALE_STRING is used to compare items as strings, based on the current locale. // SORT_NATURAL (int) - SORT_NATURAL is used to compare items as strings using "natural ordering" like natsort(). // SORT_FLAG_CASE (int) - SORT_FLAG_CASE can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively. As of PHP 8.2.0, only ASCII case folding will be done. // Filter flags: // ARRAY_FILTER_USE_KEY (int) - ARRAY_FILTER_USE_KEY is used with array_filter() to pass each key as the first argument to the given callback function. // ARRAY_FILTER_USE_BOTH (int) - ARRAY_FILTER_USE_BOTH is used with array_filter() to pass both value and key to the given callback function. // COUNT_NORMAL (int) - // COUNT_RECURSIVE (int) - // EXTR_OVERWRITE (int) - // EXTR_SKIP (int) - // EXTR_PREFIX_SAME (int) - // EXTR_PREFIX_ALL (int) - // EXTR_PREFIX_INVALID (int) - // EXTR_PREFIX_IF_EXISTS (int) - // EXTR_IF_EXISTS (int) - // EXTR_REFS (int) - // // LITERATURE_SOURCES // * PHP_NET (2023-09-15) // URL: https://www.php.net/manual/en/array.constants.php // PREDEFINED_CONSTANTS - END // // SORTING_ARRAYS - BEGIN // Sorting Arrays // // PHP has several functions that deal with sorting arrays, and this document exists to help sort it all out. // The main differences are: // * Some sort based on the array keys, whereas others by the values: $array['key'] = 'value'; // * Whether or not the correlation between the keys and values are maintained after the sort, which may mean the keys are reset numerically (0,1,2 ...) // * The order of the sort: alphabetical, ascending (low to high), descending (high to low), natural, random, or user defined // * Note: All of these sort functions act directly on the array variable itself, as opposed to returning a new sorted array // * If any of these sort functions evaluates two members as equal then they retain their original order. Prior to PHP 8.0.0, their order were undefined (the sorting was not stable). // // Sorting function attributes // Function name | Sorts by | Maintains key association | Order of sort | Related functions // array_multisort() | value | string keys yes, int keys no | first array or sort options | array_walk() // asort() | value | yes | ascending | arsort() // arsort() | value | yes | descending | asort() // krsort() | key | yes | descending | ksort() // ksort() | key | yes | ascending | krsort() // natcasesort() | value | yes | natural, case insensitive | natsort() // natsort() | value | yes | natural | natcasesort() // rsort() | value | no | descending | sort() // shuffle() | value | no | random | array_rand() // sort() | value | no | ascending | rsort() // uasort() | value | yes | user defined | uksort() // uksort() | key | yes | user defined | uasort() // usort() | value | no | user defined | uasort() // // LITERATURE_SOURCES // * PHP_NET (2023-09-15) // URL: https://www.php.net/manual/en/array.sorting.php // SORTING_ARRAYS - END // // ARRAY_FUNCTIONS - BEGIN // Array Functions // // See Also // See also is_array(), explode(), implode(), preg_split(), and unset(). // // Table of Contents // * array_change_key_case - Changes the case of all keys in an array // * array_chunk - Split an array into chunks // * array_column - Return the values from a single column in the input array // * array_combine - Creates an array by using one array for keys and another for its values // * array_count_values - Counts the occurrences of each distinct value in an array // * array_diff_assoc - Computes the difference of arrays with additional index check // * array_diff_key - Computes the difference of arrays using keys for comparison // * array_diff_uassoc - Computes the difference of arrays with additional index check which is performed by a user supplied callback function // * array_diff_ukey - Computes the difference of arrays using a callback function on the keys for comparison // * array_diff - Computes the difference of arrays // * array_fill_keys - Fill an array with values, specifying keys // * array_fill - Fill an array with values // * array_filter - Filters elements of an array using a callback function // * array_flip - Exchanges all keys with their associated values in an array // * array_intersect_assoc - Computes the intersection of arrays with additional index check // * array_intersect_key - Computes the intersection of arrays using keys for comparison // * array_intersect_uassoc - Computes the intersection of arrays with additional index check, compares indexes by a callback function // * array_intersect_ukey - Computes the intersection of arrays using a callback function on the keys for comparison // * array_intersect - Computes the intersection of arrays // * array_is_list - Checks whether a given array is a list // * array_key_exists - Checks if the given key or index exists in the array // * array_key_first - Gets the first key of an array // * array_key_last - Gets the last key of an array // * array_keys - Return all the keys or a subset of the keys of an array // * array_map - Applies the callback to the elements of the given arrays // * array_merge_recursive - Merge one or more arrays recursively // * array_merge - Merge one or more arrays // * array_multisort - Sort multiple or multi-dimensional arrays // * array_pad - Pad array to the specified length with a value // * array_pop - Pop the element off the end of array // * array_product - Calculate the product of values in an array // * array_push - Push one or more elements onto the end of array // * array_rand - Pick one or more random keys out of an array // * array_reduce - Iteratively reduce the array to a single value using a callback function // * array_replace_recursive - Replaces elements from passed arrays into the first array recursively // * array_replace - Replaces elements from passed arrays into the first array // * array_reverse - Return an array with elements in reverse order // * array_search - Searches the array for a given value and returns the first corresponding key if successful // * array_shift - Shift an element off the beginning of array // * array_slice - Extract a slice of the array // * array_splice - Remove a portion of the array and replace it with something else // * array_sum - Calculate the sum of values in an array // * array_udiff_assoc - Computes the difference of arrays with additional index check, compares data by a callback function // * array_udiff_uassoc - Computes the difference of arrays with additional index check, compares data and indexes by a callback function // * array_udiff - Computes the difference of arrays by using a callback function for data comparison // * array_uintersect_assoc - Computes the intersection of arrays with additional index check, compares data by a callback function // * array_uintersect_uassoc - Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions // * array_uintersect - Computes the intersection of arrays, compares data by a callback function // * array_unique - Removes duplicate values from an array // * array_unshift - Prepend one or more elements to the beginning of an array // * array_values - Return all the values of an array // * array_walk_recursive - Apply a user function recursively to every member of an array // * array_walk - Apply a user supplied function to every member of an array // * array - Create an array // * arsort - Sort an array in descending order and maintain index association // * asort - Sort an array in ascending order and maintain index association // * compact - Create array containing variables and their values // * count - Counts all elements in an array or in a Countable object // * current - Return the current element in an array // * each - Return the current key and value pair from an array and advance the array cursor // * end - Set the internal pointer of an array to its last element // * extract - Import variables into the current symbol table from an array // * in_array - Checks if a value exists in an array // * key_exists - Alias of array_key_exists // * key - Fetch a key from an array // * krsort - Sort an array by key in descending order // * ksort - Sort an array by key in ascending order // * list - Assign variables as if they were an array // * natcasesort - Sort an array using a case insensitive "natural order" algorithm // * natsort - Sort an array using a "natural order" algorithm // * next - Advance the internal pointer of an array // * pos - Alias of current // * prev - Rewind the internal array pointer // * range - Create an array containing a range of elements // * reset - Set the internal pointer of an array to its first element // * rsort - Sort an array in descending order // * shuffle - Shuffle an array // * sizeof - Alias of count // * sort - Sort an array in ascending order // * uasort - Sort an array with a user-defined comparison function and maintain index association // * uksort - Sort an array by keys using a user-defined comparison function // * usort - Sort an array by values using a user-defined comparison function // // LITERATURE_SOURCES // * PHP_NET (2023-09-15) // URL: https://www.php.net/manual/en/ref.array.php // ARRAY_FUNCTIONS - END // // LITERATURE_SOURCES // * PHP_NET (2023-09-15) // URL: https://www.php.net/manual/en/book.array.php // ARRAYS - END // // LANGUAGE_REFERENCE_TYPES_ARRAYS - BEGIN // Arrays (PHP Manual / Language Reference / Types / Arrays) // // An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible. // Explanation of those data structures is beyond the scope of this manual, but at least one example is provided for each of them. For more information, look towards the considerable literature that exists about this broad topic. // // Syntax // Specifying with array() // An array can be created using the array() language construct. It takes any number of comma-separated key => value pairs as arguments. // [code] // array( // key => value, // key2 => value2, // key3 => value3, // ... // ) // [/code] // The comma after the last array element is optional and can be omitted. This is usually done for single-line arrays, i.e. array(1, 2) is preferred over array(1, 2, ). For multi-line arrays on the other hand the trailing comma is commonly used, as it allows easier addition of new elements at the end. // Note: A short array syntax exists which replaces array() with []. // [example] // Example #1 A simple array // [php] // $array = array( // "foo" => "bar", // "bar" => "foo", // ); // // // Using the short array syntax // $array = [ // "foo" => "bar", // "bar" => "foo", // ]; // [/php] // [/example] // The key can either be an int or a string. The value can be of any type. // Additionally the following key casts will occur: // * Strings containing valid decimal ints, unless the number is preceded by a + sign, will be cast to the int type. E.g. the key "8" will actually be stored under 8. On the other hand "08" will not be cast, as it isn't a valid decimal integer. // * Floats are also cast to ints, which means that the fractional part will be truncated. E.g. the key 8.7 will actually be stored under 8. // * Bools are cast to ints, too, i.e. the key true will actually be stored under 1 and the key false under 0. // * Null will be cast to the empty string, i.e. the key null will actually be stored under "". // * Arrays and objects can not be used as keys. Doing so will result in a warning: Illegal offset type. // If multiple elements in the array declaration use the same key, only the last one will be used as all others are overwritten. // [example] // Example #2 Type Casting and Overwriting example // [php] // $array = array( // 1 => "a", // "1" => "b", // 1.5 => "c", // true => "d", // ); // var_dump($array); // [/php] // The above example will output: // [result] // array(1) { // [1]=> // string(1) "d" // } // [/result] // [/example] // As all the keys in the above example are cast to 1, the value will be overwritten on every new element and the last assigned value "d" is the only one left over. // PHP arrays can contain int and string keys at the same time as PHP does not distinguish between indexed and associative arrays. // [example] // Example #3 Mixed int and string keys // [php] // $array = array( // "foo" => "bar", // "bar" => "foo", // 100 => -100, // -100 => 100, // ); // var_dump($array); // [/php] // The above example will output: // [result] // array(4) { // ["foo"]=> // string(3) "bar" // ["bar"]=> // string(3) "foo" // [100]=> // int(-100) // [-100]=> // int(100) // } // [/result] // [/example] // The key is optional. If it is not specified, PHP will use the increment of the largest previously used int key. // [example] // Example #4 Indexed arrays without key // [php] // $array = array("foo", "bar", "hello", "world"); // var_dump($array); // [/php] // The above example will output: // [result] // array(4) { // [0]=> // string(3) "foo" // [1]=> // string(3) "bar" // [2]=> // string(5) "hello" // [3]=> // string(5) "world" // } // [/result] // [/example] // It is possible to specify the key only for some elements and leave it out for others: // [example] // Example #5 Keys not on all elements // [php] // $array = array( // "a", // "b", // 6 => "c", // "d", // ); // var_dump($array); // [/php] // The above example will output: // [result] // array(4) { // [0]=> // string(1) "a" // [1]=> // string(1) "b" // [6]=> // string(1) "c" // [7]=> // string(1) "d" // } // [/result] // [/example] // As you can see the last value "d" was assigned the key 7. This is because the largest integer key before that was 6. // [example] // Example #6 Complex Type Casting and Overwriting example // This example includes all variations of type casting of keys and overwriting of elements. // [php] // $array = array( // 1 => 'a', // '1' => 'b', // the value "a" will be overwritten by "b" // 1.5 => 'c', // the value "b" will be overwritten by "c" // -1 => 'd', // '01' => 'e', // as this is not an integer string it will NOT override the key for 1 // '1.5' => 'f', // as this is not an integer string it will NOT override the key for 1 // true => 'g', // the value "c" will be overwritten by "g" // false => 'h', // '' => 'i', // null => 'j', // the value "i" will be overwritten by "j" // 'k', // value "k" is assigned the key 2. This is because the largest integer key before that was 1 // 2 => 'l', // the value "k" will be overwritten by "l" // ); // // var_dump($array); // [/php] // The above example will output: // [result] // array(7) { // [1]=> // string(1) "g" // [-1]=> // string(1) "d" // ["01"]=> // string(1) "e" // ["1.5"]=> // string(1) "f" // [0]=> // string(1) "h" // [""]=> // string(1) "j" // [2]=> // string(1) "l" // } // [/result] // [/example] // Accessing array elements with square bracket syntax // Array elements can be accessed using the array[key] syntax. // [example] // Example #7 Accessing array elements // [php] // $array = array( // "foo" => "bar", // 42 => 24, // "multi" => array( // "dimensional" => array( // "array" => "foo" // ) // ) // ); // // var_dump($array["foo"]); // var_dump($array[42]); // var_dump($array["multi"]["dimensional"]["array"]); // [/php] // The above example will output: // [result] // string(3) "bar" // int(24) // string(3) "foo" // [/result] // [/example] // Note: Prior to PHP 8.0.0, square brackets and curly braces could be used interchangeably for accessing array elements (e.g. $array[42] and $array{42} would both do the same thing in the example above). The curly brace syntax was deprecated as of PHP 7.4.0 and no longer supported as of PHP 8.0.0. // [example] // Example #8 Array dereferencing // [php] // function getArray() { // return array(1, 2, 3); // } // // $secondElement = getArray()[1]; // [/php] // [/example] // Note: Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an E_WARNING-level error message (E_NOTICE-level prior to PHP 8.0.0) will be issued, and the result will be null. // Note: Array dereferencing a scalar value which is not a string yields null. Prior to PHP 7.4.0, that did not issue an error message. As of PHP 7.4.0, this issues E_NOTICE; as of PHP 8.0.0, this issues E_WARNING. // // Creating/modifying with square bracket syntax // An existing array can be modified by explicitly setting values in it. // This is done by assigning values to the array, specifying the key in brackets. The key can also be omitted, resulting in an empty pair of brackets ([]). // [code] // $arr[key] = value; // $arr[] = value; // // key may be an int or string // // value may be any value of any type // [/code] // If $arr doesn't exist yet or is set to null or false, it will be created, so this is also an alternative way to create an array. This practice is however discouraged because if $arr already contains some value (e.g. string from request variable) then this value will stay in the place and [] may actually stand for string access operator. It is always better to initialize a variable by a direct assignment. // Note: As of PHP 7.1.0, applying the empty index operator on a string throws a fatal error. Formerly, the string was silently converted to an array. // Note: As of PHP 8.1.0, creating a new array from false value is deprecated. Creating a new array from null and undefined values is still allowed. // To change a certain value, assign a new value to that element using its key. To remove a key/value pair, call the unset() function on it. // [php] // $arr = array(5 => 1, 12 => 2); // // $arr[] = 56; // This is the same as $arr[13] = 56; // // at this point of the script // // $arr["x"] = 42; // This adds a new element to // // the array with key "x" // // unset($arr[5]); // This removes the element from the array // // unset($arr); // This deletes the whole array // [/php] // Note: // As mentioned above, if no key is specified, the maximum of the existing int indices is taken, and the new key will be that maximum value plus 1 (but at least 0). If no int indices exist yet, the key will be 0 (zero). // Note that the maximum integer key used for this need not currently exist in the array. It need only have existed in the array at some time since the last time the array was re-indexed. The following example illustrates: // [example] // [php] // // Create a simple array. // $array = array(1, 2, 3, 4, 5); // print_r($array); // // // Now delete every item, but leave the array itself intact: // foreach ($array as $i => $value) { // unset($array[$i]); // } // print_r($array); // // // Append an item (note that the new key is 5, instead of 0). // $array[] = 6; // print_r($array); // // // Re-index: // $array = array_values($array); // $array[] = 7; // print_r($array); // [/php] // The above example will output: // [result] // Array // ( // [0] => 1 // [1] => 2 // [2] => 3 // [3] => 4 // [4] => 5 // ) // Array // ( // ) // Array // ( // [5] => 6 // ) // Array // ( // [0] => 6 // [1] => 7 // ) // [/result] // [/example] // // Array destructuring // Arrays can be destructured using the [] (as of PHP 7.1.0) or list() language constructs. These constructs can be used to destructure an array into distinct variables. // [php] // $source_array = ['foo', 'bar', 'baz']; // // [$foo, $bar, $baz] = $source_array; // // echo $foo; // prints "foo" // echo $bar; // prints "bar" // echo $baz; // prints "baz" // [/php] // Array destructuring can be used in foreach to destructure a multi-dimensional array while iterating over it. // [php] // $source_array = [ // [1, 'John'], // [2, 'Jane'], // ]; // // foreach ($source_array as [$id, $name]) { // // logic here with $id and $name // } // [/php] // Array elements will be ignored if the variable is not provided. Array destructuring always starts at index 0. // [php] // $source_array = ['foo', 'bar', 'baz']; // // // Assign the element at index 2 to the variable $baz // [, , $baz] = $source_array; // // echo $baz; // prints "baz" // [/php] // As of PHP 7.1.0, associative arrays can be destructured too. This also allows for easier selection of the right element in numerically indexed arrays as the index can be explicitly specified. // [php] // $source_array = ['foo' => 1, 'bar' => 2, 'baz' => 3]; // // // Assign the element at index 'baz' to the variable $three // ['baz' => $three] = $source_array; // // echo $three; // prints 3 // // $source_array = ['foo', 'bar', 'baz']; // // // Assign the element at index 2 to the variable $baz // [2 => $baz] = $source_array; // // echo $baz; // prints "baz" // [/php] // Array destructuring can be used for easy swapping of two variables. // [php] // $a = 1; // $b = 2; // // [$b, $a] = [$a, $b]; // // echo $a; // prints 2 // echo $b; // prints 1 // [/php] // Note: The spread operator (...) is not supported in assignments. // Note: Attempting to access an array key which has not been defined is the same as accessing any other undefined variable: an E_WARNING-level error message (E_NOTICE-level prior to PHP 8.0.0) will be issued, and the result will be null. // // Useful functions // There are quite a few useful functions for working with arrays. See the array functions section. // Note: // The unset() function allows removing keys from an array. Be aware that the array will not be reindexed. If a true "remove and shift" behavior is desired, the array can be reindexed using the array_values() function. // [php] // $a = array(1 => 'one', 2 => 'two', 3 => 'three'); // unset($a[2]); // /* will produce an array that would have been defined as // $a = array(1 => 'one', 3 => 'three'); // and NOT // $a = array(1 => 'one', 2 =>'three'); // */ // // $b = array_values($a); // // Now $b is array(0 => 'one', 1 =>'three') // [/php] // The foreach control structure exists specifically for arrays. It provides an easy way to traverse an array. // // Array do's and don'ts // // Why is $foo[bar] wrong? // Always use quotes around a string literal array index. For example, $foo['bar'] is correct, while $foo[bar] is not. But why? It is common to encounter this kind of syntax in old scripts: // [example] // [php] // $foo[bar] = 'enemy'; // echo $foo[bar]; // // etc // [/php] // [/example] // This is wrong, but it works. The reason is that this code has an undefined constant (bar) rather than a string ('bar' - notice the quotes). It works because PHP automatically converts a bare string (an unquoted string which does not correspond to any known symbol) into a string which contains the bare string. For instance, if there is no defined constant named bar, then PHP will substitute in the string 'bar' and use that. // Warning: The fallback to treat an undefined constant as bare string issues an error of level E_NOTICE. This has been deprecated as of PHP 7.2.0, and issues an error of level E_WARNING. As of PHP 8.0.0, it has been removed and throws an Error exception. // Note: This does not mean to always quote the key. Do not quote keys which are constants or variables, as this will prevent PHP from interpreting them. // [example] // [php] // error_reporting(E_ALL); // ini_set('display_errors', true); // ini_set('html_errors', false); // // Simple array: // $array = array(1, 2); // $count = count($array); // for ($i = 0; $i < $count; $i++) { // echo "\nChecking $i: \n"; // echo "Bad: " . $array['$i'] . "\n"; // echo "Good: " . $array[$i] . "\n"; // echo "Bad: {$array['$i']}\n"; // echo "Good: {$array[$i]}\n"; // } // [/php] // The above example will output: // [result] // Checking 0: // Notice: Undefined index: $i in /path/to/script.html on line 9 // Bad: // Good: 1 // Notice: Undefined index: $i in /path/to/script.html on line 11 // Bad: // Good: 1 // // Checking 1: // Notice: Undefined index: $i in /path/to/script.html on line 9 // Bad: // Good: 2 // Notice: Undefined index: $i in /path/to/script.html on line 11 // Bad: // Good: 2 // [/result] // [/example] // More examples to demonstrate this behaviour: // [example] // [php] // // Show all errors // error_reporting(E_ALL); // // $arr = array('fruit' => 'apple', 'veggie' => 'carrot'); // // // Correct // print $arr['fruit']; // apple // print $arr['veggie']; // carrot // // // Incorrect. This works but also throws a PHP error of level E_NOTICE because // // of an undefined constant named fruit // // // // Notice: Use of undefined constant fruit - assumed 'fruit' in... // print $arr[fruit]; // apple // // // This defines a constant to demonstrate what's going on. The value 'veggie' // // is assigned to a constant named fruit. // define('fruit', 'veggie'); // // // Notice the difference now // print $arr['fruit']; // apple // print $arr[fruit]; // carrot // // // The following is okay, as it's inside a string. Constants are not looked for // // within strings, so no E_NOTICE occurs here // print "Hello $arr[fruit]"; // Hello apple // // // With one exception: braces surrounding arrays within strings allows constants // // to be interpreted // print "Hello {$arr[fruit]}"; // Hello carrot // print "Hello {$arr['fruit']}"; // Hello apple // // // This will not work, and will result in a parse error, such as: // // Parse error: parse error, expecting T_STRING' or T_VARIABLE' or T_NUM_STRING' // // This of course applies to using superglobals in strings as well // print "Hello $arr['fruit']"; // print "Hello $_GET['foo']"; // // // Concatenation is another option // print "Hello " . $arr['fruit']; // Hello apple // [/php] // [/example] // When error_reporting is set to show E_NOTICE level errors (by setting it to E_ALL, for example), such uses will become immediately visible. By default, error_reporting is set not to show notices. // As stated in the syntax section, what's inside the square brackets ('[' and ']') must be an expression. This means that code like this works: // [example] // [php] // echo $arr[somefunc($bar)]; // [/php] // [/example] // This is an example of using a function return value as the array index. PHP also knows about constants: // [example] // [php] // $error_descriptions[E_ERROR] = "A fatal error has occurred"; // $error_descriptions[E_WARNING] = "PHP issued a warning"; // $error_descriptions[E_NOTICE] = "This is just an informal notice"; // [/php] // [/example] // 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: // [example] // [php] // $error_descriptions[1] = "A fatal error has occurred"; // $error_descriptions[2] = "PHP issued a warning"; // $error_descriptions[8] = "This is just an informal notice"; // [/php] // [/example] // because E_ERROR equals 1, etc. // // So why is it bad then? // At some point in the future, the PHP team might want to add another constant or keyword, or a constant in other code may interfere. For example, it is already wrong to use the words empty and default this way, since they are reserved keywords. // Note: To reiterate, inside a double-quoted string, it's valid to not surround array indexes with quotes so "$foo[bar]" is valid. See the above examples for details on why as well as the section on variable parsing in strings. // // Converting to array // For any of the types int, float, string, bool and resource, converting a value to an array results in an array with a single element with index zero and the value of the scalar which was converted. In other words, (array)$scalarValue is exactly the same as array($scalarValue). // If an object is converted to an array, the result is an array whose elements are the object's properties. The keys are the member variable names, with a few notable exceptions: integer properties are unaccessible; private variables have the class name prepended to the variable name; protected variables have a '*' prepended to the variable name. These prepended values have NUL bytes on either side. Uninitialized typed properties are silently discarded. // [example] // [php] // // class A { // private $B; // protected $C; // public $D; // function __construct() // { // $this->{1} = null; // } // } // // var_export((array) new A()); // [/php] // The above example will output: // [result] // array ( // '' . "\0" . 'A' . "\0" . 'B' => NULL, // '' . "\0" . '*' . "\0" . 'C' => NULL, // 'D' => NULL, // 1 => NULL, // ) // [/result] // [/example] // These NUL can result in some unexpected behaviour: // [example] // [php] // // class A { // private $A; // This will become '\0A\0A' // } // // class B extends A { // private $A; // This will become '\0B\0A' // public $AA; // This will become 'AA' // } // // var_dump((array) new B()); // [/php] // The above example will output: // [result] // array(3) { // ["BA"]=> // NULL // ["AA"]=> // NULL // ["AA"]=> // NULL // } // [/result] // [/example] // The above will appear to have two keys named 'AA', although one of them is actually named '\0A\0A'. // Converting null to an array results in an empty array. // // Comparing // It is possible to compare arrays with the array_diff() function and with array operators. // // Array unpacking // An array prefixed by ... will be expanded in place during array definition. Only arrays and objects which implement Traversable can be expanded. Array unpacking with ... is available as of PHP 7.4.0. // It's possible to expand multiple times, and add normal elements before or after the ... operator: // [example] // Example #9 Simple array unpacking // [php] // // Using short array syntax. // // Also, works with array() syntax. // $arr1 = [1, 2, 3]; // $arr2 = [...$arr1]; //[1, 2, 3] // $arr3 = [0, ...$arr1]; //[0, 1, 2, 3] // $arr4 = [...$arr1, ...$arr2, 111]; //[1, 2, 3, 1, 2, 3, 111] // $arr5 = [...$arr1, ...$arr1]; //[1, 2, 3, 1, 2, 3] // // function getArr() { // return ['a', 'b']; // } // $arr6 = [...getArr(), 'c' => 'd']; //['a', 'b', 'c' => 'd'] // [/php] // [/example] // Unpacking an array with the ... operator follows the semantics of the array_merge() function. That is, later string keys overwrite earlier ones and integer keys are renumbered: // [example] // Example #10 Array unpacking with duplicate key // [php] // // string key // $arr1 = ["a" => 1]; // $arr2 = ["a" => 2]; // $arr3 = ["a" => 0, ...$arr1, ...$arr2]; // var_dump($arr3); // ["a" => 2] // // // integer key // $arr4 = [1, 2, 3]; // $arr5 = [4, 5, 6]; // $arr6 = [...$arr4, ...$arr5]; // var_dump($arr6); // [1, 2, 3, 4, 5, 6] // // Which is [0 => 1, 1 => 2, 2 => 3, 3 => 4, 4 => 5, 5 => 6] // // where the original integer keys have not been retained. // [/php] // [/example] // Note: Keys that are neither integers nor strings throw a TypeError. Such keys can only be generated by a Traversable object. // Note: // Prior to PHP 8.1, unpacking an array which has a string key is not supported: // [example] // [php] // // $arr1 = [1, 2, 3]; // $arr2 = ['a' => 4]; // $arr3 = [...$arr1, ...$arr2]; // // Fatal error: Uncaught Error: Cannot unpack array with string keys in example.php:5 // // $arr4 = [1, 2, 3]; // $arr5 = [4, 5]; // $arr6 = [...$arr4, ...$arr5]; // works. [1, 2, 3, 4, 5] // [/php] // [/example] // // [examples] // Examples // [example] // The array type in PHP is very versatile. Here are some examples: // [php] // // This: // $a = array( 'color' => 'red', // 'taste' => 'sweet', // 'shape' => 'round', // 'name' => 'apple', // 4 // key will be 0 // ); // // $b = array('a', 'b', 'c'); // // // . . .is completely equivalent with this: // $a = array(); // $a['color'] = 'red'; // $a['taste'] = 'sweet'; // $a['shape'] = 'round'; // $a['name'] = 'apple'; // $a[] = 4; // key will be 0 // // $b = array(); // $b[] = 'a'; // $b[] = 'b'; // $b[] = 'c'; // // // After the above code is executed, $a will be the array // // array('color' => 'red', 'taste' => 'sweet', 'shape' => 'round', // // 'name' => 'apple', 0 => 4), and $b will be the array // // array(0 => 'a', 1 => 'b', 2 => 'c'), or simply array('a', 'b', 'c'). // [/php] // [/example] // [example] // Example #11 Using array() // [php] // // Array as (property-)map // $map = array( 'version' => 4, // 'OS' => 'Linux', // 'lang' => 'english', // 'short_tags' => true // ); // // // strictly numerical keys // $array = array( 7, // 8, // 0, // 156, // -10 // ); // // this is the same as array(0 => 7, 1 => 8, ...) // // $switching = array( 10, // key = 0 // 5 => 6, // 3 => 7, // 'a' => 4, // 11, // key = 6 (maximum of integer-indices was 5) // '8' => 2, // key = 8 (integer!) // '02' => 77, // key = '02' // 0 => 12 // the value 10 will be overwritten by 12 // ); // // // empty array // $empty = array(); // [/php] // [/example] // [example] // Example #12 Collection // [php] // $colors = array('red', 'blue', 'green', 'yellow'); // // foreach ($colors as $color) { // echo "Do you like $color?\n"; // } // // [/php] // The above example will output: // [result] // Do you like red? // Do you like blue? // Do you like green? // Do you like yellow? // [/result] // [/example] // Changing the values of the array directly is possible by passing them by reference. // [example] // Example #13 Changing element in the loop // [php] // foreach ($colors as &$color) { // $color = strtoupper($color); // } // unset($color); /* ensure that following writes to // $color will not modify the last array element */ // // print_r($colors); // [/php] // The above example will output: // [result] // Array // ( // [0] => RED // [1] => BLUE // [2] => GREEN // [3] => YELLOW // ) // [/result] // [/example] // This example creates a one-based array. // [example] // Example #14 One-based index // [php] // $firstquarter = array(1 => 'January', 'February', 'March'); // print_r($firstquarter); // [/php] // The above example will output: // [result] // Array // ( // [1] => 'January' // [2] => 'February' // [3] => 'March' // ) // [/result] // [/example] // [example] // Example #15 Filling an array // [php] // // fill an array with all items from a directory // $handle = opendir('.'); // while (false !== ($file = readdir($handle))) { // $files[] = $file; // } // closedir($handle); // [/php] // [/example] // Arrays are ordered. The order can be changed using various sorting functions. See the array functions section for more information. The count() function can be used to count the number of items in an array. // [example] // Example #16 Sorting an array // [php] // sort($files); // print_r($files); // [/php] // [/example] // Because the value of an array can be anything, it can also be another array. This enables the creation of recursive and multi-dimensional arrays. // [example] // Example #17 Recursive and multi-dimensional arrays // [php] // $fruits = array ( "fruits" => array ( "a" => "orange", // "b" => "banana", // "c" => "apple" // ), // "numbers" => array ( 1, // 2, // 3, // 4, // 5, // 6 // ), // "holes" => array ( "first", // 5 => "second", // "third" // ) // ); // // // Some examples to address values in the array above // echo $fruits["holes"][5]; // prints "second" // echo $fruits["fruits"]["a"]; // prints "orange" // unset($fruits["holes"][0]); // remove "first" // // // Create a new multi-dimensional array // $juices["apple"]["green"] = "good"; // [/php] // [/example] // Array assignment always involves value copying. Use the reference operator to copy an array by reference. // [example] // [php] // $arr1 = array(2, 3); // $arr2 = $arr1; // $arr2[] = 4; // $arr2 is changed, // // $arr1 is still array(2, 3) // // $arr3 = &$arr1; // $arr3[] = 4; // now $arr1 and $arr3 are the same // [/php] // [/example] // [/examples] // // LITERATURE_SOURCES // * PHP_NET (2023-09-15) // URL: https://www.php.net/manual/en/language.types.array.php // LANGUAGE_REFERENCE_TYPES_ARRAYS - END // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_CHANGE_KEY_CASE // ============================== PUBLIC // ============================== ABOUT // Changes the case of all keys in an array. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_change_key_case() - PHP_4 >= PHP_4_2_0, PHP_5, PHP_7, PHP_8 // ============================== USING CONSTANTS (1) // CASE_LOWER - array_change_key_case() // ============================== CODE function php_variable_array_array_change_key_case($array, $case = CASE_LOWER) { $return_array_change_key_case = null; // ========== ARRAY_CHANGE_KEY_CASE - BEGIN // ===== ABOUT // Changes the case of all keys in an array // ===== DESCRIPTION // Returns an array with all keys from array lowercased or uppercased. Numbered indices are left as is. // ===== SUPPORTED // PHP_4 >= PHP_4_2_0, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_change_key_case(array $array, int $case = CASE_LOWER): array // ===== CODE $return_array_change_key_case = array_change_key_case( $array, // array array - The array to work on $case // int case - Either CASE_UPPER or CASE_LOWER (default) ); // Return Values // Returns an array with its keys lower or uppercased. // // [examples] // Examples // [example] // Example #1 array_change_key_case() example // [php] // $input_array = array("FirSt" => 1, "SecOnd" => 4); // print_r(array_change_key_case($input_array, CASE_UPPER)); // [/php] // The above example will output: // [result] // Array // ( // [FIRST] => 1 // [SECOND] => 4 // ) // [/result] // [/example] // [/examples] // // Notes // Note: If an array has indices that will be the same once run through this function (e.g. "keY" and "kEY"), the value that is later in the array will override other indices. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-18) // URL: https://www.php.net/manual/en/function.array-change-key-case.php // ========== ARRAY_CHANGE_KEY_CASE - END // SYNTAX: // array array_change_key_case(array $array, int $case = CASE_LOWER) return $return_array_change_key_case; // array } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_CHANGE_KEY_CASE // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_CHUNK // ============================== PUBLIC // ============================== ABOUT // Split an array into chunks. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_chunk() - PHP_4 >= PHP_4_2_0, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array_chunk($array, $length, $preserve_keys = false) { $return_array_chunk = null; // ========== ARRAY_CHUNK - BEGIN // ===== ABOUT // Split an array into chunks // ===== DESCRIPTION // Chunks an array into arrays with length elements. The last chunk may contain less than length elements. // ===== SUPPORTED // PHP_4 >= PHP_4_2_0, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_chunk(array $array, int $length, bool $preserve_keys = false): array // ===== CODE $return_array_chunk = array_chunk( $array, // array array - The array to work on $length, // int length - The size of each chunk $preserve_keys // bool preserve_keys - When set to true keys will be preserved. Default is false which will reindex the chunk numerically ); // Return Values // Returns a multidimensional numerically indexed array, starting with zero, with each dimension containing length elements. // // Errors/Exceptions // If length is less than 1, a ValueError will be thrown. // // Changelog // Version - Description // 8.0.0 - If length is less than 1, a ValueError will be thrown now; previously, an error of level E_WARNING has been raised instead, and the function returned null. // // [examples] // Examples // [example] // Example #1 array_chunk() example // [php] // $input_array = array('a', 'b', 'c', 'd', 'e'); // print_r(array_chunk($input_array, 2)); // print_r(array_chunk($input_array, 2, true)); // [/php] // The above example will output: // [result] // Array // ( // [0] => Array // ( // [0] => a // [1] => b // ) // // [1] => Array // ( // [0] => c // [1] => d // ) // // [2] => Array // ( // [0] => e // ) // // ) // Array // ( // [0] => Array // ( // [0] => a // [1] => b // ) // // [1] => Array // ( // [2] => c // [3] => d // ) // // [2] => Array // ( // [4] => e // ) // // ) // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-19) // URL: https://www.php.net/manual/en/function.array-chunk.php // ========== ARRAY_CHUNK - END // SYNTAX: // array array_chunk(array $array, int $length, bool $preserve_keys = false) return $return_array_chunk; // array } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_CHUNK // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_COLUMN // ============================== OFFLINE // ============================== ABOUT // Return the values from a single column in the input array. // ============================== SUPPORT // PHP_5 - PHP_8 // ============================== USING FUNCTIONS (1) // array_column() - PHP_5 >= PHP_5_5_0, PHP_7, PHP_8 // ============================== CODE /* function php_variable_array_array_column($array, $column_key, $index_key = null) { $return_array_column = null; // ========== ARRAY_COLUMN - BEGIN // ===== ABOUT // Return the values from a single column in the input array // ===== DESCRIPTION // array_column() returns the values from a single column of the array, identified by the column_key. Optionally, an index_key may be provided to index the values in the returned array by the values from the index_key column of the input array. // ===== SUPPORTED // PHP_5 >= PHP_5_5_0, PHP_7, PHP_8 // ===== SYNTAX // array_column(array $array, int|string|null $column_key, int|string|null $index_key = null): array // ===== CODE $return_array_column = array_column( $array, // array array - A multi-dimensional array or an array of objects from which to pull a column of values from. If an array of objects is provided, then public properties can be directly pulled. In order for protected or private properties to be pulled, the class must implement both the __get() and __isset() magic methods. $column_key, // int|string|null column_key - The column of values to return. This value may be an integer key of the column you wish to retrieve, or it may be a string key name for an associative array or property name. It may also be null to return complete arrays or objects (this is useful together with index_key to reindex the array). $index_key // int|string|null index_key - The column to use as the index/keys for the returned array. This value may be the integer key of the column, or it may be the string key name. The value is cast as usual for array keys (however, prior to PHP 8.0.0, objects supporting conversion to string were also allowed). ); // Return Values // Returns an array of values representing a single column from the input array. // // Changelog // Version - Description // 8.0.0 - Objects in columns indicated by index_key parameter will no longer be cast to string and will now throw a TypeError instead. // // [examples] // Examples // [example] // Example #1 Get the column of first names from a recordset // [php] // // Array representing a possible record set returned from a database // $records = array( // array( // 'id' => 2135, // 'first_name' => 'John', // 'last_name' => 'Doe', // ), // array( // 'id' => 3245, // 'first_name' => 'Sally', // 'last_name' => 'Smith', // ), // array( // 'id' => 5342, // 'first_name' => 'Jane', // 'last_name' => 'Jones', // ), // array( // 'id' => 5623, // 'first_name' => 'Peter', // 'last_name' => 'Doe', // ) // ); // // $first_names = array_column($records, 'first_name'); // print_r($first_names); // [/php] // The above example will output: // [result] // Array // ( // [0] => John // [1] => Sally // [2] => Jane // [3] => Peter // ) // [/result] // [/example] // [example] // Example #2 Get the column of last names from a recordset, indexed by the "id" column // [php] // // Using the $records array from Example #1 // $last_names = array_column($records, 'last_name', 'id'); // print_r($last_names); // [/php] // The above example will output: // [result] // Array // ( // [2135] => Doe // [3245] => Smith // [5342] => Jones // [5623] => Doe // ) // [/result] // [/example] // [example] // Example #3 Get the column of usernames from the public "username" property of an object // [php] // // class User // { // public $username; // // public function __construct(string $username) // { // $this->username = $username; // } // } // // $users = [ // new User('user 1'), // new User('user 2'), // new User('user 3'), // ]; // // print_r(array_column($users, 'username')); // [/php] // The above example will output: // [result] // Array // ( // [0] => user 1 // [1] => user 2 // [2] => user 3 // ) // [/result] // [/example] // [example] // Example #4 Get the column of names from the private "name" property of an object using the magic __get() method. // [php] // // class Person // { // private $name; // // public function __construct(string $name) // { // $this->name = $name; // } // // public function __get($prop) // { // return $this->$prop; // } // // public function __isset($prop) : bool // { // return isset($this->$prop); // } // } // // $people = [ // new Person('Fred'), // new Person('Jane'), // new Person('John'), // ]; // // print_r(array_column($people, 'name')); // [/php] // The above example will output: // [result] // Array // ( // [0] => Fred // [1] => Jane // [2] => John // ) // [/result] // If __isset() is not provided, then an empty array will be returned. // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-19) // URL: https://www.php.net/manual/en/function.array-column.php // ========== ARRAY_COLUMN - END // SYNTAX: // array array_column(array $array, int|string|null $column_key, int|string|null $index_key = null) return $return_array_column; // array } */ // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_COLUMN // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_COMBINE // ============================== OFFLINE // ============================== ABOUT // Creates an array by using one array for keys and another for its values. // ============================== SUPPORT // PHP_5 - PHP_8 // ============================== USING FUNCTIONS (1) // array_combine() - PHP_5, PHP_7, PHP_8 // ============================== CODE /* function php_variable_array_array_combine($keys, $values) { $return_array_combine = null; // ========== ARRAY_COMBINE - BEGIN // ===== ABOUT // Creates an array by using one array for keys and another for its values // ===== DESCRIPTION // Creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values. // ===== SUPPORTED // PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_combine(array $keys, array $values): array // ===== CODE $return_array_combine = array_combine( $keys, // array keys - Array of keys to be used. Illegal values for key will be converted to string. $values // array values - Array of values to be used ); // Return Values // Returns the combined array. // // Errors/Exceptions // As of PHP 8.0.0, a ValueError is thrown if the number of elements in keys and values does not match. Prior to PHP 8.0.0, a E_WARNING was emitted instead. // // Changelog // Version - Description // 8.0.0 - array_combine() will now throw a ValueError if the number of elements for each array is not equal; previously this function returned false instead. // // [examples] // Examples // [example] // Example #1 A simple array_combine() example // [php] // $a = array('green', 'red', 'yellow'); // $b = array('avocado', 'apple', 'banana'); // $c = array_combine($a, $b); // // print_r($c); // [/php] // The above example will output: // [result] // Array // ( // [green] => avocado // [red] => apple // [yellow] => banana // ) // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-19) // URL: https://www.php.net/manual/en/function.array-combine.php // ========== ARRAY_COMBINE - END // SYNTAX: // array array_combine(array $keys, array $values) return $return_array_combine; // array } */ // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_COMBINE // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_COUNT_VALUES // ============================== PUBLIC // ============================== ABOUT // Counts the occurrences of each distinct value in an array. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_count_values() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array_count_values($array) { $return_array_count_values = null; // ========== ARRAY_COUNT_VALUES - BEGIN // ===== ABOUT // Counts the occurrences of each distinct value in an array // ===== DESCRIPTION // array_count_values() returns an array using the values of array (which must be ints or strings) as keys and their frequency in array as values. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_count_values(array $array): array // ===== CODE $return_array_count_values = array_count_values( $array // array array - The array of values to count ); // Return Values // Returns an associative array of values from array as keys and their count as value. // // Errors/Exceptions // Throws E_WARNING for every element which is not string or int. // // [examples] // Examples // [example] // Example #1 array_count_values() example // [php] // $array = array(1, "hello", 1, "world", "hello"); // print_r(array_count_values($array)); // [/php] // The above example will output: // [result] // Array // ( // [1] => 2 // [hello] => 2 // [world] => 1 // ) // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-19) // URL: https://www.php.net/manual/en/function.array-count-values.php // ========== ARRAY_COUNT_VALUES - END // SYNTAX: // array array_count_values(array $array) return $return_array_count_values; // array } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_COUNT_VALUES // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_DIFF_ASSOC // ============================== PUBLIC // ============================== ABOUT // Computes the difference of arrays with additional index check. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_diff_assoc() - PHP_4 >= PHP_4_3_0, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array_diff_assoc($array, $arrays) { $return_array_diff_assoc = null; // ========== ARRAY_DIFF_ASSOC - BEGIN // ===== ABOUT // Computes the difference of arrays with additional index check // ===== DESCRIPTION // Compares array against arrays and returns the difference. Unlike array_diff() the array keys are also used in the comparison. // ===== SUPPORTED // PHP_4 >= PHP_4_3_0, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_diff_assoc(array $array, array ...$arrays): array // ===== CODE $return_array_diff_assoc = array_diff_assoc( $array, // array array - The array to compare from $arrays // array arrays - Arrays to compare against ); // Return Values // Returns an array containing all the values from array that are not present in any of the other arrays. // // Changelog // Version - Description // 8.0.0 - This function can now be called with only one parameter. Formerly, at least two parameters have been required. // // [examples] // Examples // [example] // Example #1 array_diff_assoc() example // In this example the "a" => "green" pair is present in both arrays and thus it is not in the output from the function. Unlike this, the pair 0 => "red" is in the output because the key of "red" is automatically assigned to 0 in the first array, whereas it is assigned to 1 in the second array as the key 0 is already taken by yellow. // [php] // $array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red"); // $array2 = array("a" => "green", "yellow", "red"); // $result = array_diff_assoc($array1, $array2); // print_r($result); // [/php] // The above example will output: // [result] // Array // ( // [b] => brown // [c] => blue // [0] => red // ) // [/result] // [/example] // [example] // Example #2 array_diff_assoc() example // Two values from key => value pairs are considered equal only if (string) $elem1 === (string) $elem2 . In other words a strict check takes place so the string representations must be the same. // [php] // $array1 = array(0, 1, 2); // $array2 = array("00", "01", "2"); // $result = array_diff_assoc($array1, $array2); // print_r($result); // [/php] // The above example will output: // [result] // Array // ( // [0] => 0 // [1] => 1 // ) // [/result] // [/example] // [/examples] // // Notes // Note: This function only checks one dimension of an n-dimensional array. It is possible to check deeper dimensions by using, for example, array_diff_assoc($array1[0], $array2[0]);. // Note: Ensure arguments are passed in the correct order when comparing similar arrays with more keys. The new array should be the first in the list. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-19) // URL: https://www.php.net/manual/en/function.array-diff-assoc.php // ========== ARRAY_DIFF_ASSOC - END // SYNTAX: // array array_diff_assoc(array $array, array $arrays) return $return_array_diff_assoc; // array } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_DIFF_ASSOC // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_DIFF_KEY // ============================== OFFLINE // ============================== ABOUT // Computes the difference of arrays using keys for comparison. // ============================== SUPPORT // PHP_5 - PHP_8 // ============================== USING FUNCTIONS (1) // array_diff_key() - PHP_5 >= PHP_5_1_0, PHP_7, PHP_8 // ============================== CODE /* function php_variable_array_array_diff_key($array, $arrays) { $return_array_diff_key = null; // ========== ARRAY_DIFF_KEY - BEGIN // ===== ABOUT // Computes the difference of arrays using keys for comparison // ===== DESCRIPTION // Compares the keys from array against the keys from arrays and returns the difference. This function is like array_diff() except the comparison is done on the keys instead of the values. // ===== SUPPORTED // PHP_5 >= PHP_5_1_0, PHP_7, PHP_8 // ===== SYNTAX // array_diff_key(array $array, array ...$arrays): array // ===== CODE $return_array_diff_key = array_diff_key( $array, // array array - The array to compare from $arrays // array arrays - Arrays to compare against ); // Return Values // Returns an array containing all the entries from array whose keys are absent from all of the other arrays. // // Changelog // Version - Description // 8.0.0 - This function can now be called with only one parameter. Formerly, at least two parameters have been required. // // [examples] // Examples // [example] // Example #1 array_diff_key() example // The two keys from the key => value pairs are considered equal only if (string) $key1 === (string) $key2 . In other words a strict type check is executed so the string representation must be the same. // [php] // $array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4); // $array2 = array('green' => 5, 'yellow' => 7, 'cyan' => 8); // // var_dump(array_diff_key($array1, $array2)); // [/php] // The above example will output: // [result] // array(3) { // ["blue"]=> // int(1) // ["red"]=> // int(2) // ["purple"]=> // int(4) // } // [/result] // [/example] // [example] // [php] // $array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4); // $array2 = array('green' => 5, 'yellow' => 7, 'cyan' => 8); // $array3 = array('blue' => 6, 'yellow' => 7, 'mauve' => 8); // // var_dump(array_diff_key($array1, $array2, $array3)); // [/php] The above example will output: // [result] // array(2) { // ["red"]=> // int(2) // ["purple"]=> // int(4) // } // [/result] // [/example] // [/examples] // // Notes // Note: This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff_key($array1[0], $array2[0]);. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-19) // URL: https://www.php.net/manual/en/function.array-diff-key.php // ========== ARRAY_DIFF_KEY - END // SYNTAX: // array array_diff_key(array $array, array $arrays) return $return_array_diff_key; // array } */ // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_DIFF_KEY // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_DIFF_UASSOC // ============================== OFFLINE // ============================== ABOUT // Computes the difference of arrays with additional index check which is performed by a user supplied callback function. // ============================== SUPPORT // PHP_5 - PHP_8 // ============================== USING FUNCTIONS (1) // array_diff_uassoc() - PHP_5, PHP_7, PHP_8 // ============================== CODE /* function php_variable_array_array_diff_uassoc($array, $arrays, $key_compare_func) { $return_array_diff_uassoc = null; // ========== ARRAY_DIFF_UASSOC - BEGIN // ===== ABOUT // Computes the difference of arrays with additional index check which is performed by a user supplied callback function // ===== DESCRIPTION // Compares array against arrays and returns the difference. Unlike array_diff() the array keys are used in the comparison. // Unlike array_diff_assoc() a user supplied callback function is used for the indices comparison, not internal function. // ===== SUPPORTED // PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_diff_uassoc(array $array, array ...$arrays, callable $key_compare_func): array // ===== CODE $return_array_diff_uassoc = array_diff_uassoc( $array, // array - The array to compare from $arrays, // array arrays - Arrays to compare against $key_compare_func // callable key_compare_func - The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. // callback(mixed $a, mixed $b): int // Caution: Returning non-integer values from the comparison function, such as float, will result in an internal cast to int of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal. ); // Return Values // Returns an array containing all the entries from array that are not present in any of the other arrays. // // [examples] // Examples // [example] // Example #1 array_diff_uassoc() example // In this example the "a" => "green" pair is present in both arrays and thus it is not in the output from the function. Unlike this, the pair 0 => "red" is in the output because the key of "red" is automatically assigned to 0 in the first array, whereas it is assigned to 1 in the second array as the key 0 is already taken by yellow. // [php] // function key_compare_func($a, $b) // { // return $a <=> $b; // } // // $array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red"); // $array2 = array("a" => "green", "yellow", "red"); // $result = array_diff_uassoc($array1, $array2, "key_compare_func"); // print_r($result); // [/php] // The above example will output: // [result] // Array // ( // [b] => brown // [c] => blue // [0] => red // ) // [/result] // The equality of 2 indices is checked by the user supplied callback function. // [/example] // [/examples] // // Notes // Note: This function only checks one dimension of an n-dimensional array. It is possible to check deeper dimensions by using, for example, array_diff_uassoc($array1[0], $array2[0], "key_compare_func");. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-19) // URL: https://www.php.net/manual/en/function.array-diff-uassoc.php // ========== ARRAY_DIFF_UASSOC - END // SYNTAX: // array array_diff_uassoc(array $array, array $arrays, callable $key_compare_func) return $return_array_diff_uassoc; // array } */ // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_DIFF_UASSOC // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_DIFF_UKEY // ============================== OFFLINE // ============================== ABOUT // Computes the difference of arrays using a callback function on the keys for comparison. // ============================== SUPPORT // PHP_5 - PHP_8 // ============================== USING FUNCTIONS (1) // array_diff_ukey() - PHP_5 >= PHP_5_1_0, PHP_7, PHP_8 // ============================== CODE /* function php_variable_array_array_diff_ukey($array, $arrays, $key_compare_func) { $return_array_diff_ukey = false; // ========== ARRAY_DIFF_UKEY - BEGIN // ===== ABOUT // Computes the difference of arrays using a callback function on the keys for comparison // ===== DESCRIPTION // Compares the keys from array against the keys from arrays and returns the difference. This function is like array_diff() except the comparison is done on the keys instead of the values. // Unlike array_diff_key() a user supplied callback function is used for the indices comparison, not internal function. // ===== SUPPORTED // PHP_5 >= PHP_5_1_0, PHP_7, PHP_8 // ===== SYNTAX // array_diff_ukey(array $array, array ...$arrays, callable $key_compare_func): array // ===== CODE $return_array_diff_ukey = array_diff_ukey( $array, // array array - The array to compare from $arrays, // array arrays - Arrays to compare against $key_compare_func // callable key_compare_func - The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. // callback(mixed $a, mixed $b): int // Caution: Returning non-integer values from the comparison function, such as float, will result in an internal cast to int of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal. ); // Return Values // Returns an array containing all the entries from array that are not present in any of the other arrays. // // [examples] // Examples // [example] // Example #1 array_diff_ukey() example // [php] // function key_compare_func($key1, $key2) // { // if ($key1 == $key2) // return 0; // else if ($key1 > $key2) // return 1; // else // return -1; // } // // $array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4); // $array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan' => 8); // // var_dump(array_diff_ukey($array1, $array2, 'key_compare_func')); // [/php] // The above example will output: // [result] // array(2) { // ["red"]=> // int(2) // ["purple"]=> // int(4) // } // [/result] // [/example] // [/examples] // // Notes // Note: This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff_ukey($array1[0], $array2[0], 'callback_func');. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-19) // URL: https://www.php.net/manual/en/function.array-diff-ukey.php // ========== ARRAY_DIFF_UKEY - END // SYNTAX: // array array_diff_ukey(array $array, array $arrays, callable $key_compare_func) return $return_array_diff_ukey; // array } */ // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_DIFF_UKEY // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_DIFF // ============================== PUBLIC // ============================== ABOUT // Computes the difference of arrays. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_diff() - PHP_4 >= PHP_4_0_1, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array_diff($array, $arrays) { $return_array_diff = null; // ========== ARRAY_DIFF - BEGIN // ===== ABOUT // Computes the difference of arrays // ===== DESCRIPTION // Compares array against one or more other arrays and returns the values in array that are not present in any of the other arrays. // ===== SUPPORTED // PHP_4 >= PHP_4_0_1, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_diff(array $array, array ...$arrays): array // ===== CODE $return_array_diff = array_diff( $array, // array array - The array to compare from $arrays // array arrays - Arrays to compare against ); // Return Values // Returns an array containing all the entries from array that are not present in any of the other arrays. Keys in the array array are preserved. // // Changelog // Version - Description // 8.0.0 - This function can now be called with only one parameter. Formerly, at least two parameters have been required. // // [examples] // Examples // [example] // Example #1 array_diff() example // [php] // $array1 = array("a" => "green", "red", "blue", "red"); // $array2 = array("b" => "green", "yellow", "red"); // $result = array_diff($array1, $array2); // // print_r($result); // [/php] // Multiple occurrences in $array1 are all treated the same way. This will output : // [result] // Array // ( // [1] => blue // ) // [/result] // [/example] // [example] // Example #2 array_diff() example with non-matching types // Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. That is, when the string representation is the same. // [php] // // This will generate a Notice that an array cannot be cast to a string. // $source = [1, 2, 3, 4]; // $filter = [3, 4, [5], 6]; // $result = array_diff($source, $filter); // // // Whereas this is fine, since the objects can cast to a string. // class S { // private $v; // // public function __construct(string $v) { // $this->v = $v; // } // // public function __toString() { // return $this->v; // } // } // // $source = [new S('a'), new S('b'), new S('c')]; // $filter = [new S('b'), new S('c'), new S('d')]; // // $result = array_diff($source, $filter); // // // $result now contains one instance of S('a'); // [/php] // To use an alternate comparison function, see array_udiff(). // [/example] // [/examples] // // Notes // Note: This function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_diff($array1[0], $array2[0]);. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-19) // URL: https://www.php.net/manual/en/function.array-diff.php // ========== ARRAY_DIFF - END // SYNTAX: // array array_diff(array $array, array $arrays) return $return_array_diff; // array } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_DIFF // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_FILL_KEYS // ============================== OFFLINE // ============================== ABOUT // Fill an array with values, specifying keys. // ============================== SUPPORT // PHP_5 - PHP_8 // ============================== USING FUNCTIONS (1) // array_fill_keys() - PHP_5 >= PHP_5_2_0, PHP_7, PHP_8 // ============================== CODE /* function php_variable_array_array_fill_keys($keys, $value) { $return_array_fill_keys = null; // ========== ARRAY_FILL_KEYS - BEGIN // ===== ABOUT // Fill an array with values, specifying keys // ===== DESCRIPTION // Fills an array with the value of the value parameter, using the values of the keys array as keys. // ===== SUPPORTED // PHP_5 >= PHP_5_2_0, PHP_7, PHP_8 // ===== SYNTAX // array_fill_keys(array $keys, mixed $value): array // ===== CODE $return_array_fill_keys = array_fill_keys( $keys, // array keys - Array of values that will be used as keys. Illegal values for key will be converted to string. $value // mixed value - Value to use for filling ); // Return Values // Returns the filled array // // [examples] // Examples // [example] // Example #1 array_fill_keys() example // [php] // $keys = array('foo', 5, 10, 'bar'); // $a = array_fill_keys($keys, 'banana'); // print_r($a); // [/php] // The above example will output: // [result] // Array // ( // [foo] => banana // [5] => banana // [10] => banana // [bar] => banana // ) // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-19) // URL: https://www.php.net/manual/en/function.array-fill-keys.php // ========== ARRAY_FILL_KEYS - END // SYNTAX: // array array_fill_keys(array $keys, mixed $value) return $return_array_fill_keys; // array } */ // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_FILL_KEYS // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_FILL // ============================== PUBLIC // ============================== ABOUT // Fill an array with values. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_fill() - PHP_4 >= PHP_4_2_0, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array_fill($start_index, $count, $value) { $return_array_fill = null; // ========== ARRAY_FILL - BEGIN // ===== ABOUT // Fill an array with values // ===== DESCRIPTION // Fills an array with count entries of the value of the value parameter, keys starting at the start_index parameter. // ===== SUPPORTED // PHP_4 >= PHP_4_2_0, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_fill(int $start_index, int $count, mixed $value): array // ===== CODE $return_array_fill = array_fill( $start_index, // int start_index - The first index of the returned array. // If start_index is negative, the first index of the returned array will be start_index and the following indices will start from zero prior to PHP 8.0.0; as of PHP 8.0.0, negative keys are incremented normally (see example). $count, // int count - Number of elements to insert. Must be greater than or equal to zero, and less than or equal to 2147483647. $value // mixed value - Value to use for filling ); // Return Values // Returns the filled array // // Errors/Exceptions // Throws a ValueError if count is out of range. // // Changelog // Version - Description // 8.0.0 - array_fill() now throws a ValueError if count is out of range; previously E_WARNING was raised, and the function returned false. // // [examples] // Examples // [example] // Example #1 array_fill() example // [php] // $a = array_fill(5, 6, 'banana'); // print_r($a); // [/php] // The above example will output: // [result] // Array // ( // [5] => banana // [6] => banana // [7] => banana // [8] => banana // [9] => banana // [10] => banana // ) // [/result] // [/example] // [example] // Example #2 array_fill() example with a negative start index // [php] // $a = array_fill(-2, 4, 'pear'); // print_r($a); // [/php] // Output of the above example in PHP 7: // [result] // Array // ( // [-2] => pear // [0] => pear // [1] => pear // [2] => pear // ) // [/result] // Output of the above example in PHP 8: // [result] // Array // ( // [-2] => pear // [-1] => pear // [0] => pear // [1] => pear // ) // [/result] // Note that index -1 is not present prior to PHP 8.0.0. // [/example] // [/examples] // // Notes // See also the Arrays section of manual for a detailed explanation of negative keys. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-19) // URL: https://www.php.net/manual/en/function.array-fill.php // ========== ARRAY_FILL - END // SYNTAX: // array array_fill(int $start_index, int $count, mixed $value) return $return_array_fill; // array } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_FILL // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_FILTER // ============================== PUBLIC // ============================== ABOUT // Filters elements of an array using a callback function. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_filter() - PHP_4 >= PHP_4_0_6, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array_filter($array, $callback = null, $mode = 0) { $return_array_filter = null; // ========== ARRAY_FILTER - BEGIN // ===== ABOUT // Filters elements of an array using a callback function // ===== DESCRIPTION // Iterates over each value in the array passing them to the callback function. If the callback function returns true, the current value from array is returned into the result array. // Array keys are preserved, and may result in gaps if the array was indexed. The result array can be reindexed using the array_values() function. // ===== SUPPORTED // PHP_4 >= PHP_4_0_6, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_filter(array $array, ?callable $callback = null, int $mode = 0): array // ===== CODE $return_array_filter = array_filter( $array, // array array - The array to iterate over $callback, // callable callback - The callback function to use // If no callback is supplied, all empty entries of array will be removed. See empty() for how PHP defines empty in this case. $mode // int mode - Flag determining what arguments are sent to callback: // * ARRAY_FILTER_USE_KEY - pass key as the only argument to callback instead of the value // * ARRAY_FILTER_USE_BOTH - pass both value and key as arguments to callback instead of the value // Default is 0 which will pass value as the only argument to callback instead. ); // Return Values // Returns the filtered array. // // Changelog // Version - Description // 8.0.0 - callback is nullable now. // 8.0.0 - If callback expects a parameter to be passed by reference, this function will now emit an E_WARNING. // // [examples] // Examples // [example] // Example #1 array_filter() example // [php] // function odd($var) // { // // returns whether the input integer is odd // return $var & 1; // } // // function even($var) // { // // returns whether the input integer is even // return !($var & 1); // } // // $array1 = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5]; // $array2 = [6, 7, 8, 9, 10, 11, 12]; // // echo "Odd :\n"; // print_r(array_filter($array1, "odd")); // echo "Even:\n"; // print_r(array_filter($array2, "even")); // [/php] // The above example will output: // [result] // Odd : // Array // ( // [a] => 1 // [c] => 3 // [e] => 5 // ) // Even: // Array // ( // [0] => 6 // [2] => 8 // [4] => 10 // [6] => 12 // ) // [/result] // [/example] // [example] // Example #2 array_filter() without callback // [php] // // $entry = [ // 0 => 'foo', // 1 => false, // 2 => -1, // 3 => null, // 4 => '', // 5 => '0', // 6 => 0, // ]; // // print_r(array_filter($entry)); // [/php] // The above example will output: // [result] // Array // ( // [0] => foo // [2] => -1 // ) // [/result] // [/example] // [example] // Example #3 array_filter() with mode // [php] // // $arr = ['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4]; // // var_dump(array_filter($arr, function($k) { // return $k == 'b'; // }, ARRAY_FILTER_USE_KEY)); // // var_dump(array_filter($arr, function($v, $k) { // return $k == 'b' || $v == 4; // }, ARRAY_FILTER_USE_BOTH)); // [/php] // The above example will output: // [result] // array(1) { // ["b"]=> // int(2) // } // array(2) { // ["b"]=> // int(2) // ["d"]=> // int(4) // } // [/result] // [/example] // [/examples] // // Notes // Caution: If the array is changed from the callback function (e.g. element added, deleted or unset) the behavior of this function is undefined. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-19) // URL: https://www.php.net/manual/en/function.array-filter.php // ========== ARRAY_FILTER - END // SYNTAX: // array array_filter(array $array, callable $callback = null, int $mode = 0) return $return_array_filter; // array } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_FILTER // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_FLIP // ============================== PUBLIC // ============================== ABOUT // Exchanges all keys with their associated values in an array. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_flip() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array_flip($array) { $return_array_flip = null; // ========== ARRAY_FLIP - BEGIN // ===== ABOUT // Exchanges all keys with their associated values in an array // ===== DESCRIPTION // array_flip() returns an array in flip order, i.e. keys from array become values and values from array become keys. // Note that the values of array need to be valid keys, i.e. they need to be either int or string. A warning will be emitted if a value has the wrong type, and the key/value pair in question will not be included in the result. // If a value has several occurrences, the latest key will be used as its value, and all others will be lost. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_flip(array $array): array // ===== CODE $return_array_flip = array_flip( $array // array array - An array of key/value pairs to be flipped. ); // Return Values // Returns the flipped array. // // [examples] // Examples // [example] // Example #1 array_flip() example // [php] // $input = array("oranges", "apples", "pears"); // $flipped = array_flip($input); // // print_r($flipped); // [/php] // The above example will output: // [result] // Array // ( // [oranges] => 0 // [apples] => 1 // [pears] => 2 // ) // [/result] // [/example] // [example] // Example #2 array_flip() example : collision // [php] // $input = array("a" => 1, "b" => 1, "c" => 2); // $flipped = array_flip($input); // // print_r($flipped); // [/php] // The above example will output: // [result] // Array // ( // [1] => b // [2] => c // ) // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-18) // URL: https://www.php.net/manual/en/function.array-flip.php // ========== ARRAY_FLIP - END // SYNTAX: // array array_flip(array $array) return $return_array_flip; // array } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_FLIP // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_INTERSECT_ASSOC // ============================== PUBLIC // ============================== ABOUT // Computes the intersection of arrays with additional index check. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_intersect_assoc() - PHP_4 >= PHP_4_3_0, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array_intersect_assoc($array, $arrays) { $return_array_intersect_assoc = null; // ========== ARRAY_INTERSECT_ASSOC - BEGIN // ===== ABOUT // Computes the intersection of arrays with additional index check // ===== DESCRIPTION // array_intersect_assoc() returns an array containing all the values of array that are present in all the arguments. Note that the keys are also used in the comparison unlike in array_intersect(). // ===== SUPPORTED // PHP_4 >= PHP_4_3_0, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_intersect_assoc(array $array, array ...$arrays): array // ===== CODE $return_array_intersect_assoc = array_intersect_assoc( $array, // array array - The array with master values to check. $arrays // array arrays - Arrays to compare values against. ); // Return Values // Returns an associative array containing all the values in array that are present in all of the arguments. // // Changelog // Version - Description // 8.0.0 - This function can now be called with only one parameter. Formerly, at least two parameters have been required. // // [examples] // Examples // [example] // Example #1 array_intersect_assoc() example // [php] // $array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red"); // $array2 = array("a" => "green", "b" => "yellow", "blue", "red"); // $result_array = array_intersect_assoc($array1, $array2); // print_r($result_array); // [/php] // The above example will output: // [result] // Array // ( // [a] => green // ) // [/result] // In our example you see that only the pair "a" => "green" is present in both arrays and thus is returned. The value "red" is not returned because in $array1 its key is 0 while the key of "red" in $array2 is 1, and the key "b" is not returned because its values are different in each array. // The two values from the key => value pairs are considered equal only if (string) $elem1 === (string) $elem2 . In other words a strict type check is executed so the string representation must be the same. // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.array-intersect-assoc.php // ========== ARRAY_INTERSECT_ASSOC - END // SYNTAX: // array array_intersect_assoc(array $array, array $arrays) return $return_array_intersect_assoc; // array } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_INTERSECT_ASSOC // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_INTERSECT_KEY // ============================== OFFLINE // ============================== ABOUT // Computes the intersection of arrays using keys for comparison. // ============================== SUPPORT // PHP_5 - PHP_8 // ============================== USING FUNCTIONS (1) // array_intersect_key() - PHP_5 >= PHP_5_1_0, PHP_7, PHP_8 // ============================== CODE /* function php_variable_array_array_intersect_key($array, $arrays) { $return_array_intersect_key = null; // ========== ARRAY_INTERSECT_KEY - BEGIN // ===== ABOUT // Computes the intersection of arrays using keys for comparison // ===== DESCRIPTION // array_intersect_key() returns an array containing all the entries of array which have keys that are present in all the arguments. // ===== SUPPORTED // PHP_5 >= PHP_5_1_0, PHP_7, PHP_8 // ===== SYNTAX // array_intersect_key(array $array, array ...$arrays): array // ===== CODE $return_array_intersect_key = array_intersect_key( $array, // array array - The array with master keys to check. $arrays // array arrays - Arrays to compare keys against. ); // Return Values // Returns an associative array containing all the entries of array which have keys that are present in all arguments. // // Changelog // Version - Description // 8.0.0 - This function can now be called with only one parameter. Formerly, at least two parameters have been required. // // [examples] // Examples // [example] // Example #1 array_intersect_key() example // [php] // $array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4); // $array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan' => 8); // // var_dump(array_intersect_key($array1, $array2)); // [/php] // The above example will output: // [result] // array(2) { // ["blue"]=> // int(1) // ["green"]=> // int(3) // } // [/result] // In our example you see that only the keys 'blue' and 'green' are present in both arrays and thus returned. Also notice that the values for the keys 'blue' and 'green' differ between the two arrays. A match still occurs because only the keys are checked. The values returned are those of array. // The two keys from the key => value pairs are considered equal only if (string) $key1 === (string) $key2 . In other words a strict type check is executed so the string representation must be the same. // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.array-intersect-key.php // ========== ARRAY_INTERSECT_KEY - END // SYNTAX: // array array_intersect_key(array $array, array $arrays) return $return_array_intersect_key; // array } */ // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_INTERSECT_KEY // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_INTERSECT_UASSOC // ============================== PUBLIC // ============================== ABOUT // Computes the intersection of arrays with additional index check, compares indexes by a callback function. // ============================== SUPPORT // PHP_5 - PHP_8 // ============================== USING FUNCTIONS (1) // array_intersect_uassoc() - PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array_intersect_uassoc($array, $arrays, $key_compare_func) { $return_array_intersect_uassoc = null; // ========== ARRAY_INTERSECT_UASSOC - BEGIN // ===== ABOUT // Computes the intersection of arrays with additional index check, compares indexes by a callback function // ===== DESCRIPTION // array_intersect_uassoc() returns an array containing all the values of array that are present in all the arguments. Note that the keys are used in the comparison unlike in array_intersect(). // ===== SUPPORTED // PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_intersect_uassoc(array $array, array ...$arrays, callable $key_compare_func): array // ===== CODE $return_array_intersect_uassoc = array_intersect_uassoc( $array, // array array - Initial array for comparison of the arrays. $arrays, // array arrays - Arrays to compare keys against. $key_compare_func // callable key_compare_func - The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. // callback(mixed $a, mixed $b): int // Caution: Returning non-integer values from the comparison function, such as float, will result in an internal cast to int of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal. ); // Return Values // Returns the values of array whose values exist in all of the arguments. // // [examples] // Examples // [example] // Example #1 array_intersect_uassoc() example // [php] // $array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red"); // $array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red"); // // print_r(array_intersect_uassoc($array1, $array2, "strcasecmp")); // [/php] // The above example will output: // [result] // Array // ( // [b] => brown // ) // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.array-intersect-uassoc.php // ========== ARRAY_INTERSECT_UASSOC - END // SYNTAX: // array array_intersect_uassoc(array $array, array $arrays, callable $key_compare_func) return $return_array_intersect_uassoc; // array } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_INTERSECT_UASSOC // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_INTERSECT_UKEY // ============================== OFFLINE // ============================== ABOUT // Computes the intersection of arrays using a callback function on the keys for comparison. // ============================== SUPPORT // PHP_5 - PHP_8 // ============================== USING FUNCTIONS (1) // array_intersect_ukey() - PHP_5 >= PHP_5_1_0, PHP_7, PHP_8 // ============================== CODE /* function php_variable_array_array_intersect_ukey($array, $arrays, $key_compare_func) { $return_array_intersect_ukey = null; // ========== ARRAY_INTERSECT_UKEY - BEGIN // ===== ABOUT // Computes the intersection of arrays using a callback function on the keys for comparison // ===== DESCRIPTION // array_intersect_ukey() returns an array containing all the values of array which have matching keys that are present in all the arguments. // ===== SUPPORTED // PHP_5 >= PHP_5_1_0, PHP_7, PHP_8 // ===== SYNTAX // array_intersect_ukey(array $array, array ...$arrays, callable $key_compare_func): array // ===== CODE $return_array_intersect_ukey = array_intersect_ukey( $array, // array array - Initial array for comparison of the arrays. $arrays, // array arrays - Arrays to compare keys against. $key_compare_func // callable key_compare_func - The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. // callback(mixed $a, mixed $b): int // Caution: Returning non-integer values from the comparison function, such as float, will result in an internal cast to int of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal. ); // Return Values // Returns the values of array whose keys exist in all the arguments. // // [examples] // Examples // [example] // Example #1 array_intersect_ukey() example // [php] // function key_compare_func($key1, $key2) // { // if ($key1 == $key2) // return 0; // else if ($key1 > $key2) // return 1; // else // return -1; // } // // $array1 = array('blue' => 1, 'red' => 2, 'green' => 3, 'purple' => 4); // $array2 = array('green' => 5, 'blue' => 6, 'yellow' => 7, 'cyan' => 8); // // var_dump(array_intersect_ukey($array1, $array2, 'key_compare_func')); // [/php] // The above example will output: // [result] // array(2) { // ["blue"]=> // int(1) // ["green"]=> // int(3) // } // [/result] // In our example you see that only the keys 'blue' and 'green' are present in both arrays and thus returned. Also notice that the values for the keys 'blue' and 'green' differ between the two arrays. A match still occurs because only the keys are checked. The values returned are those of array. // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.array-intersect-ukey.php // ========== ARRAY_INTERSECT_UKEY - END // SYNTAX: // array array_intersect_ukey(array $array, array $arrays, callable $key_compare_func) return $return_array_intersect_ukey; // array } */ // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_INTERSECT_UKEY // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_INTERSECT // ============================== PUBLIC // ============================== ABOUT // Computes the intersection of arrays. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_intersect() - PHP_4 >= PHP_4_0_1, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array_intersect($array, $arrays) { $return_array_intersect = null; // ========== ARRAY_INTERSECT - BEGIN // ===== ABOUT // Computes the intersection of arrays // ===== DESCRIPTION // array_intersect() returns an array containing all the values of array that are present in all the arguments. Note that keys are preserved. // ===== SUPPORTED // PHP_4 >= PHP_4_0_1, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_intersect(array $array, array ...$arrays): array // ===== CODE $return_array_intersect = array_intersect( $array, // array array - The array with master values to check. $arrays // array arrays - Arrays to compare values against. ); // Return Values // Returns an array containing all of the values in array whose values exist in all of the parameters. // // Changelog // Version - Description // 8.0.0 - This function can now be called with only one parameter. Formerly, at least two parameters have been required. // // [examples] // Examples // [example] // Example #1 array_intersect() example // [php] // $array1 = array("a" => "green", "red", "blue"); // $array2 = array("b" => "green", "yellow", "red"); // $result = array_intersect($array1, $array2); // print_r($result); // [/php] // The above example will output: // [result] // Array // ( // [a] => green // [0] => red // ) // [/result] // [/example] // [/examples] // // Notes // Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2. In words: when the string representation is the same. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.array-intersect.php // ========== ARRAY_INTERSECT - END // SYNTAX: // array array_intersect(array $array, array $arrays) return $return_array_intersect; // array } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_INTERSECT // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_IS_LIST // ============================== OFFLINE // ============================== ABOUT // Checks whether a given array is a list. // ============================== SUPPORT // PHP_8 // ============================== USING FUNCTIONS (1) // array_is_list() - PHP_8 >= PHP_8_1_0 // ============================== CODE /* function php_variable_array_array_is_list($array) { $return_array_is_list = false; // ========== ARRAY_IS_LIST - BEGIN // ===== ABOUT // Checks whether a given array is a list // ===== DESCRIPTION // Determines if the given array is a list. An array is considered a list if its keys consist of consecutive numbers from 0 to count($array)-1. // ===== SUPPORTED // PHP_8 >= PHP_8_1_0 // ===== SYNTAX // array_is_list(array $array): bool // ===== CODE $return_array_is_list = array_is_list( $array // array array - The array being evaluated. ); // Return Values // Returns true if array is a list, false otherwise. // // [examples] // Examples // [example] // Example #1 array_is_list() example // [php] // array_is_list([]); // true // array_is_list(['apple', 2, 3]); // true // array_is_list([0 => 'apple', 'orange']); // true // // // The array does not start at 0 // array_is_list([1 => 'apple', 'orange']); // false // // // The keys are not in the correct order // array_is_list([1 => 'apple', 0 => 'orange']); // false // // // Non-integer keys // array_is_list([0 => 'apple', 'foo' => 'bar']); // false // // // Non-consecutive keys // array_is_list([0 => 'apple', 2 => 'bar']); // false // [/php] // [/example] // [/examples] // // Notes // Note: This function returns true on empty arrays. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.array-is-list.php // ========== ARRAY_IS_LIST - END // SYNTAX: // bool array_is_list(array $array) return $return_array_is_list; // bool } */ // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_IS_LIST // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_KEY_EXISTS // ============================== PUBLIC // ============================== ABOUT // Checks if the given key or index exists in the array. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_key_exists() - PHP_4 >= PHP_4_0_7, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array_key_exists($key, $array) { $return_array_key_exists = false; // ========== ARRAY_KEY_EXISTS - BEGIN // ===== ABOUT // Checks if the given key or index exists in the array // ===== DESCRIPTION // array_key_exists() returns true if the given key is set in the array. key can be any value possible for an array index. // ===== SUPPORTED // PHP_4 >= PHP_4_0_7, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_key_exists(string|int $key, array $array): bool // ===== CODE $return_array_key_exists = array_key_exists( $key, // string|int $key - Value to check. $array // array $array - An array with keys to check. ); // Return Values // Returns true on success or false on failure. // Note: array_key_exists() will search for the keys in the first dimension only. Nested keys in multidimensional arrays will not be found. // // [examples] // Examples // [example] // Example #1 array_key_exists() example // [php] // $search_array = array('first' => 1, 'second' => 4); // if (array_key_exists('first', $search_array)) { // echo "The 'first' element is in the array"; // } // [/php] // [/example] // [example] // Example #2 array_key_exists() vs isset() // isset() does not return true for array keys that correspond to a null value, while array_key_exists() does. // [php] // $search_array = array('first' => null, 'second' => 4); // // // returns false // isset($search_array['first']); // // // returns true // array_key_exists('first', $search_array); // [/php] // [/example] // [/examples] // // Notes // Note: // For backward compatibility reasons, array_key_exists() will also return true if key is a property defined within an object given as array. This behaviour is deprecated as of PHP 7.4.0, and removed as of PHP 8.0.0. // To check whether a property exists in an object, property_exists() should be used. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-19) // URL: https://www.php.net/manual/en/function.array-key-exists.php // ========== ARRAY_KEY_EXISTS - END // SYNTAX: // bool array_key_exists(string|int $key, array $array) return $return_array_key_exists; // bool } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_KEY_EXISTS // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_KEY_FIRST // ============================== OFFLINE // ============================== ABOUT // Gets the first key of an array. // ============================== SUPPORT // PHP_7 - PHP_8 // ============================== USING FUNCTIONS (1) // array_key_first() - PHP_7 >= PHP_7_3_0, PHP_8 // ============================== CODE /* function php_variable_array_array_key_first($array) { $return_array_key_first = null; // ========== ARRAY_KEY_FIRST - BEGIN // ===== ABOUT // Gets the first key of an array // ===== DESCRIPTION // Get the first key of the given array without affecting the internal array pointer. // ===== SUPPORTED // PHP_7 >= PHP_7_3_0, PHP_8 // ===== SYNTAX // array_key_first(array $array): int|string|null // ===== CODE $return_array_key_first = array_key_first( $array // array array - An array. ); // Return Values // Returns the first key of array if the array is not empty; null otherwise. // // [examples] // Examples // [example] // Example #1 Basic array_key_first() Usage // [php] // $array = ['a' => 1, 'b' => 2, 'c' => 3]; // // $firstKey = array_key_first($array); // // var_dump($firstKey); // [/php] // The above example will output: // [result] // string(1) "a" // [/result] // [/example] // [/examples] // // Notes // Tip: There are several ways to provide this functionality for versions prior to PHP 7.3.0. It is possible to use array_keys(), but that may be rather inefficient. It is also possible to use reset() and key(), but that may change the internal array pointer. An efficient solution, which does not change the internal array pointer, written as polyfill: // [php] // if (!function_exists('array_key_first')) { // function array_key_first(array $arr) { // foreach($arr as $key => $unused) { // return $key; // } // return NULL; // } // } // [/php] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-19) // URL: https://www.php.net/manual/en/function.array-key-first.php // ========== ARRAY_KEY_FIRST - END // SYNTAX: // int|string|null array_key_first(array $array) return $return_array_key_first; // int|string|null } */ // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_KEY_FIRST // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_KEY_LAST // ============================== OFFLINE // ============================== ABOUT // Gets the last key of an array. // ============================== SUPPORT // PHP_7 - PHP_8 // ============================== USING FUNCTIONS (1) // array_key_last() - PHP_7 >= PHP_7_3_0, PHP_8 // ============================== CODE /* function php_variable_array_array_key_last($array) { $return_array_key_last = null; // ========== ARRAY_KEY_LAST - BEGIN // ===== ABOUT // Gets the last key of an array // ===== DESCRIPTION // Get the last key of the given array without affecting the internal array pointer. // ===== SUPPORTED // PHP_7 >= PHP_7_3_0, PHP_8 // ===== SYNTAX // array_key_last(array $array): int|string|null // ===== CODE $return_array_key_last = array_key_last( $array // array array - An array. ); // Return Values // Returns the last key of array if the array is not empty; null otherwise. // ===== LITERATURE_SOURCES // * PHP_NET (2023-07-18) // URL: https://www.php.net/manual/en/function.array-key-last.php // ========== ARRAY_KEY_LAST - END // SYNTAX: // int|string|null array_key_last(array $array) return $return_array_key_last; // int|string|null } */ // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_KEY_LAST // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_KEYS // ============================== PUBLIC // ============================== ABOUT // Return all the keys or a subset of the keys of an array. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_keys() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array_keys($array, $filter_value, $strict = false) { $return_array_keys = null; // ========== ARRAY_KEYS - BEGIN // ===== ABOUT // Return all the keys or a subset of the keys of an array // ===== DESCRIPTION // array_keys() returns the keys, numeric and string, from the array. // If a filter_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_keys(array $array): array // // array_keys(array $array, mixed $filter_value, bool $strict = false): array // ===== CODE $return_array_keys = array_keys( $array, // array array - An array containing keys to return. $filter_value, // mixed filter_value - If specified, then only keys containing this value are returned. $strict // bool strict - Determines if strict comparison (===) should be used during the search. ); // Return Values // Returns an array of all the keys in array. // // [examples] // Examples // [example] // Example #1 array_keys() example // [php] // $array = array(0 => 100, "color" => "red"); // print_r(array_keys($array)); // // $array = array("blue", "red", "green", "blue", "blue"); // print_r(array_keys($array, "blue")); // // $array = array("color" => array("blue", "red", "green"), // "size" => array("small", "medium", "large")); // print_r(array_keys($array)); // [/php] // The above example will output: // [result] // Array // ( // [0] => 0 // [1] => color // ) // Array // ( // [0] => 0 // [1] => 3 // [2] => 4 // ) // Array // ( // [0] => color // [1] => size // ) // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-19) // URL: https://www.php.net/manual/en/function.array-keys.php // ========== ARRAY_KEYS - END // SYNTAX: // array array_keys(array $array, mixed $filter_value, bool $strict = false) return $return_array_keys; // array } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_KEYS // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_MAP // ============================== PUBLIC // ============================== ABOUT // Applies the callback to the elements of the given arrays. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_map() - PHP_4 >= PHP_4_0_6, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array_map($callback, $array, $arrays) { $return_array_map = null; // ========== ARRAY_MAP - BEGIN // ===== ABOUT // Applies the callback to the elements of the given arrays // ===== DESCRIPTION // array_map() returns an array containing the results of applying the callback to the corresponding value of array (and arrays if more arrays are provided) used as arguments for the callback. The number of parameters that the callback function accepts should match the number of arrays passed to array_map(). Excess input arrays are ignored. An ArgumentCountError is thrown if an insufficient number of arguments is provided. // ===== SUPPORTED // PHP_4 >= PHP_4_0_6, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_map(?callable $callback, array $array, array ...$arrays): array // ===== CODE $return_array_map = array_map( $callback, // callable callback - A callable to run for each element in each array. // null can be passed as a value to callback to perform a zip operation on multiple arrays. If only array is provided, array_map() will return the input array. $array, // array array - An array to run through the callback function. $arrays // array arrays - Supplementary variable list of array arguments to run through the callback function. ); // Return Values // Returns an array containing the results of applying the callback function to the corresponding value of array (and arrays if more arrays are provided) used as arguments for the callback. // The returned array will preserve the keys of the array argument if and only if exactly one array is passed. If more than one array is passed, the returned array will have sequential integer keys. // // Changelog // Version - Description // 8.0.0 - If callback expects a parameter to be passed by reference, this function will now emit an E_WARNING. // // [examples] // Examples // [example] // Example #1 array_map() example // [php] // function cube($n) // { // return ($n * $n * $n); // } // // $a = [1, 2, 3, 4, 5]; // $b = array_map('cube', $a); // print_r($b); // [/php] // This makes $b have: // [result] // Array // ( // [0] => 1 // [1] => 8 // [2] => 27 // [3] => 64 // [4] => 125 // ) // [/result] // [/example] // [example] // Example #2 array_map() using a lambda function // [php] // $func = function(int $value): int { // return $value * 2; // }; // // print_r(array_map($func, range(1, 5))); // // // Or as of PHP 7.4.0: // // print_r(array_map(fn($value): int => $value * 2, range(1, 5))); // // [/php] // // [result] // Array // ( // [0] => 2 // [1] => 4 // [2] => 6 // [3] => 8 // [4] => 10 // ) // [/result] // [/example] // [example] // Example #3 array_map() - using more arrays // [php] // function show_Spanish(int $n, string $m): string // { // return "The number {$n} is called {$m} in Spanish"; // } // // function map_Spanish(int $n, string $m): array // { // return [$n => $m]; // } // // $a = [1, 2, 3, 4, 5]; // $b = ['uno', 'dos', 'tres', 'cuatro', 'cinco']; // // $c = array_map('show_Spanish', $a, $b); // print_r($c); // // $d = array_map('map_Spanish', $a , $b); // print_r($d); // [/php] // The above example will output: // [result] // // printout of $c // Array // ( // [0] => The number 1 is called uno in Spanish // [1] => The number 2 is called dos in Spanish // [2] => The number 3 is called tres in Spanish // [3] => The number 4 is called cuatro in Spanish // [4] => The number 5 is called cinco in Spanish // ) // // // printout of $d // Array // ( // [0] => Array // ( // [1] => uno // ) // // [1] => Array // ( // [2] => dos // ) // // [2] => Array // ( // [3] => tres // ) // // [3] => Array // ( // [4] => cuatro // ) // // [4] => Array // ( // [5] => cinco // ) // // ) // [/result] // Usually when using two or more arrays, they should be of equal length because the callback function is applied in parallel to the corresponding elements. If the arrays are of unequal length, shorter ones will be extended with empty elements to match the length of the longest. // An interesting use of this function is to construct an array of arrays, which can be easily performed by using null as the name of the callback function // [/example] // [example] // Example #4 Performing a zip operation of arrays // [php] // $a = [1, 2, 3, 4, 5]; // $b = ['one', 'two', 'three', 'four', 'five']; // $c = ['uno', 'dos', 'tres', 'cuatro', 'cinco']; // // $d = array_map(null, $a, $b, $c); // print_r($d); // [/php] // The above example will output: // [result] // Array // ( // [0] => Array // ( // [0] => 1 // [1] => one // [2] => uno // ) // // [1] => Array // ( // [0] => 2 // [1] => two // [2] => dos // ) // // [2] => Array // ( // [0] => 3 // [1] => three // [2] => tres // ) // // [3] => Array // ( // [0] => 4 // [1] => four // [2] => cuatro // ) // // [4] => Array // ( // [0] => 5 // [1] => five // [2] => cinco // ) // // ) // [/result] // [/example] // [example] // Example #5 null callback with only array // [php] // $array = [1, 2, 3]; // var_dump(array_map(null, $array)); // [/php] // The above example will output: // [result] // array(3) { // [0]=> // int(1) // [1]=> // int(2) // [2]=> // int(3) // } // [/result] // [/example] // [example] // Example #6 array_map() - with string keys // [php] // $arr = ['stringkey' => 'value']; // function cb1($a) { // return [$a]; // } // function cb2($a, $b) { // return [$a, $b]; // } // var_dump(array_map('cb1', $arr)); // var_dump(array_map('cb2', $arr, $arr)); // var_dump(array_map(null, $arr)); // var_dump(array_map(null, $arr, $arr)); // [/php] // The above example will output: // [result] // array(1) { // ["stringkey"]=> // array(1) { // [0]=> // string(5) "value" // } // } // array(1) { // [0]=> // array(2) { // [0]=> // string(5) "value" // [1]=> // string(5) "value" // } // } // array(1) { // ["stringkey"]=> // string(5) "value" // } // array(1) { // [0]=> // array(2) { // [0]=> // string(5) "value" // [1]=> // string(5) "value" // } // } // [/result] // [/example] // [example] // Example #7 array_map() - associative arrays // While array_map() does not directly support using the array key as an input, that may be simulated using array_keys(). // [php] // $arr = [ // 'v1' => 'First release', // 'v2' => 'Second release', // 'v3' => 'Third release', // ]; // // // Note: Before 7.4.0, use the longer syntax for anonymous functions instead. // $callback = fn(string $k, string $v): string => "$k was the $v"; // // $result = array_map($callback, array_keys($arr), array_values($arr)); // // var_dump($result); // [/php] // The above example will output: // [result] // array(3) { // [0]=> // string(24) "v1 was the First release" // [1]=> // string(25) "v2 was the Second release" // [2]=> // string(24) "v3 was the Third release" // } // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-19) // URL: https://www.php.net/manual/en/function.array-map.php // ========== ARRAY_MAP - END // SYNTAX: // array array_map(callable $callback, array $array, array $arrays) return $return_array_map; // array } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_MAP // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_MERGE_RECURSIVE // ============================== PUBLIC // ============================== ABOUT // Merge one or more arrays recursively. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_merge_recursive() - PHP_4 >= PHP_4_0_1, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array_merge_recursive($arrays) { $return_array_merge_recursive = null; // ========== ARRAY_MERGE_RECURSIVE - BEGIN // ===== ABOUT // Merge one or more arrays recursively // ===== DESCRIPTION // array_merge_recursive() merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array. // If the input arrays have the same string keys, then the values for these keys are merged together into an array, and this is done recursively, so that if one of the values is an array itself, the function will merge it with a corresponding entry in another array too. If, however, the arrays have the same numeric key, the later value will not overwrite the original value, but will be appended. // ===== SUPPORTED // PHP_4 >= PHP_4_0_1, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_merge_recursive(array ...$arrays): array // ===== CODE $return_array_merge_recursive = array_merge_recursive( $arrays // array arrays - Variable list of arrays to recursively merge. ); // Return Values // An array of values resulted from merging the arguments together. If called without any arguments, returns an empty array. // // Changelog // Version - Description // 7.4.0 - This function can now be called without any parameter. Formerly, at least one parameter has been required. // // [examples] // Examples // [example] // Example #1 array_merge_recursive() example // [php] // $ar1 = array("color" => array("favorite" => "red"), 5); // $ar2 = array(10, "color" => array("favorite" => "green", "blue")); // $result = array_merge_recursive($ar1, $ar2); // print_r($result); // [/php] // The above example will output: // [result] // Array // ( // [color] => Array // ( // [favorite] => Array // ( // [0] => red // [1] => green // ) // // [0] => blue // ) // // [0] => 5 // [1] => 10 // ) // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.array-merge-recursive.php // ========== ARRAY_MERGE_RECURSIVE - END // SYNTAX: // array array_merge_recursive(array $arrays) return $return_array_merge_recursive; // array } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_MERGE_RECURSIVE // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_MERGE // ============================== PUBLIC // ============================== ABOUT // Merge one or more arrays. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_merge() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array_merge($arrays) { $return_array_merge = null; // ========== ARRAY_MERGE - BEGIN // ===== ABOUT // Merge one or more arrays // ===== DESCRIPTION // Merges the elements of one or more arrays together so that the values of one are appended to the end of the previous one. It returns the resulting array. // If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended. // Values in the input arrays with numeric keys will be renumbered with incrementing keys starting from zero in the result array. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_merge(array ...$arrays): array // ===== CODE $return_array_merge = array_merge( $arrays // array arrays - Variable list of arrays to merge. ); // Return Values // Returns the resulting array. If called without any arguments, returns an empty array. // // Changelog // Version - Description // 7.4.0 - This function can now be called without any parameter. Formerly, at least one parameter has been required. // // [examples] // Examples // [example] // Example #1 array_merge() example // [php] // $array1 = array("color" => "red", 2, 4); // $array2 = array("a", "b", "color" => "green", "shape" => "trapezoid", 4); // $result = array_merge($array1, $array2); // print_r($result); // [/php] // The above example will output: // [result] // Array // ( // [color] => green // [0] => 2 // [1] => 4 // [2] => a // [3] => b // [shape] => trapezoid // [4] => 4 // ) // [/result] // [/example] // [example] // Example #2 Simple array_merge() example // [php] // $array1 = array(); // $array2 = array(1 => "data"); // $result = array_merge($array1, $array2); // [/php] // Don't forget that numeric keys will be renumbered! // [result] // Array // ( // [0] => data // ) // [/result] // If you want to append array elements from the second array to the first array while not overwriting the elements from the first array and not re-indexing, use the + array union operator: // [php] // $array1 = array(0 => 'zero_a', 2 => 'two_a', 3 => 'three_a'); // $array2 = array(1 => 'one_b', 3 => 'three_b', 4 => 'four_b'); // $result = $array1 + $array2; // var_dump($result); // [/php] // The keys from the first array will be preserved. If an array key exists in both arrays, then the element from the first array will be used and the matching key's element from the second array will be ignored. // [result] // array(5) { // [0]=> // string(6) "zero_a" // [2]=> // string(5) "two_a" // [3]=> // string(7) "three_a" // [1]=> // string(5) "one_b" // [4]=> // string(6) "four_b" // } // [/result] // [/example] // [example] // Example #3 array_merge() with non-array types // [php] // $beginning = 'foo'; // $end = array(1 => 'bar'); // $result = array_merge((array)$beginning, (array)$end); // print_r($result); // [/php] // The above example will output: // [result] // Array // ( // [0] => foo // [1] => bar // ) // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.array-merge.php // ========== ARRAY_MERGE - END // SYNTAX: // array array_merge(array $arrays) return $return_array_merge; // array } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_MERGE // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_MULTISORT // ============================== PUBLIC // ============================== ABOUT // Sort multiple or multi-dimensional arrays. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_multisort() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== USING CONSTANTS (2) // SORT_ASC - array_multisort() // SORT_REGULAR - array_multisort() // ============================== CODE function php_variable_array_array_multisort(& $array1, $array1_sort_order = SORT_ASC, $array1_sort_flags = SORT_REGULAR, $rest) { $return_array_multisort = false; // ========== ARRAY_MULTISORT - BEGIN // ===== ABOUT // Sort multiple or multi-dimensional arrays // ===== DESCRIPTION // array_multisort() can be used to sort several arrays at once, or a multi-dimensional array by one or more dimensions. // Associative (string) keys will be maintained, but numeric keys will be re-indexed. // Note: If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined. // Note: Resets array's internal pointer to the first element. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_multisort( // array &$array1, // mixed $array1_sort_order = SORT_ASC, // mixed $array1_sort_flags = SORT_REGULAR, // mixed ...$rest // ): bool // ===== CODE $return_array_multisort = array_multisort( $array1, // array& array1 - An array being sorted. $array1_sort_order, // mixed array1_sort_order - The order used to sort the previous array argument. Either SORT_ASC to sort ascendingly or SORT_DESC to sort descendingly. // This argument can be swapped with array1_sort_flags or omitted entirely, in which case SORT_ASC is assumed. $array1_sort_flags, // mixed array1_sort_flags - Sort options for the previous array argument: // // Sorting type flags: // * SORT_REGULAR - compare items normally (don't change types) // * SORT_NUMERIC - compare items numerically // * SORT_STRING - compare items as strings // * SORT_LOCALE_STRING - compare items as strings, based on the current locale. It uses the locale, which can be changed using setlocale() // * SORT_NATURAL - compare items as strings using "natural ordering" like natsort() // * SORT_FLAG_CASE - can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively // This argument can be swapped with array1_sort_order or omitted entirely, in which case SORT_REGULAR is assumed. $rest // mixed rest - More arrays, optionally followed by sort order and flags. Only elements corresponding to equivalent elements in previous arrays are compared. In other words, the sort is lexicographical. ); // Return Values // Returns true on success or false on failure. // // [examples] // Examples // [example] // Example #1 Sorting multiple arrays // [php] // $ar1 = array(10, 100, 100, 0); // $ar2 = array(1, 3, 2, 4); // array_multisort($ar1, $ar2); // // var_dump($ar1); // var_dump($ar2); // [/php] // In this example, after sorting, the first array will contain 0, 10, 100, 100. The second array will contain 4, 1, 2, 3. The entries in the second array corresponding to the identical entries in the first array (100 and 100) were sorted as well. // [result] // array(4) { // [0]=> int(0) // [1]=> int(10) // [2]=> int(100) // [3]=> int(100) // } // array(4) { // [0]=> int(4) // [1]=> int(1) // [2]=> int(2) // [3]=> int(3) // } // [/result] // [/example] // [example] // Example #2 Sorting multi-dimensional array // [php] // $ar = array( // array("10", 11, 100, 100, "a"), // array( 1, 2, "2", 3, 1) // ); // array_multisort($ar[0], SORT_ASC, SORT_STRING, // $ar[1], SORT_NUMERIC, SORT_DESC); // var_dump($ar); // [/php] // In this example, after sorting, the first array will transform to "10", 100, 100, 11, "a" (it was sorted as strings in ascending order). The second will contain 1, 3, "2", 2, 1 (sorted as numbers, in descending order). // [result] // array(2) { // [0]=> array(5) { // [0]=> string(2) "10" // [1]=> int(100) // [2]=> int(100) // [3]=> int(11) // [4]=> string(1) "a" // } // [1]=> array(5) { // [0]=> int(1) // [1]=> int(3) // [2]=> string(1) "2" // [3]=> int(2) // [4]=> int(1) // } // } // [/result] // [/example] // [example] // Example #3 Sorting database results // For this example, each element in the data array represents one row in a table. This type of dataset is typical of database records. // Example data: // volume | edition // -------+-------- // 67 | 2 // 86 | 1 // 85 | 6 // 98 | 2 // 86 | 6 // 67 | 7 // The data as an array, called data. This would usually, for example, be obtained by looping with mysqli_fetch_assoc(). // [php] // $data[] = array('volume' => 67, 'edition' => 2); // $data[] = array('volume' => 86, 'edition' => 1); // $data[] = array('volume' => 85, 'edition' => 6); // $data[] = array('volume' => 98, 'edition' => 2); // $data[] = array('volume' => 86, 'edition' => 6); // $data[] = array('volume' => 67, 'edition' => 7); // [/php] // In this example, we will order by volume descending, edition ascending. // We have an array of rows, but array_multisort() requires an array of columns, so we use the below code to obtain the columns, then perform the sorting. // [php] // // Obtain a list of columns // foreach ($data as $key => $row) { // $volume[$key] = $row['volume']; // $edition[$key] = $row['edition']; // } // // // you can use array_column() instead of the above code // $volume = array_column($data, 'volume'); // $edition = array_column($data, 'edition'); // // // Sort the data with volume descending, edition ascending // // Add $data as the last parameter, to sort by the common key // array_multisort($volume, SORT_DESC, $edition, SORT_ASC, $data); // [/php] // The dataset is now sorted, and will look like this: // [result] // volume | edition // -------+-------- // 98 | 2 // 86 | 1 // 86 | 6 // 85 | 6 // 67 | 2 // 67 | 7 // [/result] // [/example] // [example] // Example #4 Case insensitive sorting // Both SORT_STRING and SORT_REGULAR are case sensitive, strings starting with a capital letter will come before strings starting with a lowercase letter. // To perform a case insensitive sort, force the sorting order to be determined by a lowercase copy of the original array. // [php] // $array = array('Alpha', 'atomic', 'Beta', 'bank'); // $array_lowercase = array_map('strtolower', $array); // // array_multisort($array_lowercase, SORT_ASC, SORT_STRING, $array); // // print_r($array); // [/php] // The above example will output: // [result] // Array // ( // [0] => Alpha // [1] => atomic // [2] => bank // [3] => Beta // ) // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.array-multisort.php // ========== ARRAY_MULTISORT - END // SYNTAX: // bool array_multisort(array& $array1, mixed $array1_sort_order = SORT_ASC, mixed $array1_sort_flags = SORT_REGULAR, mixed $rest) return $return_array_multisort; // bool } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_MULTISORT // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_PAD // ============================== PUBLIC // ============================== ABOUT // Pad array to the specified length with a value. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_pad() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array_pad($array, $length, $value) { $return_array_pad = null; // ========== ARRAY_PAD - BEGIN // ===== ABOUT // Pad array to the specified length with a value // ===== DESCRIPTION // array_pad() returns a copy of the array padded to size specified by length with value value. If length is positive then the array is padded on the right, if it's negative then on the left. If the absolute value of length is less than or equal to the length of the array then no padding takes place. It is possible to add at most 1048576 elements at a time. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_pad(array $array, int $length, mixed $value): array // ===== CODE $return_array_pad = array_pad( $array, // array array - Initial array of values to pad. $length, // int length - New size of the array. $value // mixed value - Value to pad if array is less than length. ); // Return Values // Returns a copy of the array padded to size specified by length with value value. If length is positive then the array is padded on the right, if it's negative then on the left. If the absolute value of length is less than or equal to the length of the array then no padding takes place. // // [examples] // Examples // [example] // Example #1 array_pad() example // [php] // $input = array(12, 10, 9); // // $result = array_pad($input, 5, 0); // // result is array(12, 10, 9, 0, 0) // // $result = array_pad($input, -7, -1); // // result is array(-1, -1, -1, -1, 12, 10, 9) // // $result = array_pad($input, 2, "noop"); // // not padded // [/php] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-21) // URL: https://www.php.net/manual/en/function.array-pad.php // ========== ARRAY_PAD - END // SYNTAX: // array array_pad(array $array, int $length, mixed $value) return $return_array_pad; // array } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_PAD // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_POP // ============================== PUBLIC // ============================== ABOUT // Pop the element off the end of array. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_pop() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array_pop($array) { $return_array_pop = null; // ========== ARRAY_POP - BEGIN // ===== ABOUT // Pop the element off the end of array // ===== DESCRIPTION // array_pop() pops and returns the value of the last element of array, shortening the array by one element. // Note: This function will reset() the array pointer of the input array after use. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_pop(array &$array): mixed // ===== CODE $return_array_pop = array_pop( $array // array& array - The array to get the value from. ); // Return Values // Returns the value of the last element of array. If array is empty, null will be returned. // // [examples] // Examples // [example] // Example #1 array_pop() example // [php] // $stack = array("orange", "banana", "apple", "raspberry"); // $fruit = array_pop($stack); // print_r($stack); // [/php] // After this, $stack will have only 3 elements: // [result] // Array // ( // [0] => orange // [1] => banana // [2] => apple // ) // [/result] // and raspberry will be assigned to $fruit. // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-21) // URL: https://www.php.net/manual/en/function.array-pop.php // ========== ARRAY_POP - END // SYNTAX: // mixed array_pop(array& $array) return $return_array_pop; // mixed } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_POP // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_PRODUCT // ============================== OFFLINE // ============================== ABOUT // Calculate the product of values in an array. // ============================== SUPPORT // PHP_5 - PHP_8 // ============================== USING FUNCTIONS (1) // array_product() - PHP_5 >= PHP_5_1_0, PHP_7, PHP_8 // ============================== CODE /* function php_variable_array_array_product($array) { $return_array_product = 0; // ========== ARRAY_PRODUCT - BEGIN // ===== ABOUT // Calculate the product of values in an array // ===== DESCRIPTION // array_product() returns the product of values in an array. // ===== SUPPORTED // PHP_5 >= PHP_5_1_0, PHP_7, PHP_8 // ===== SYNTAX // array_product(array $array): int|float // ===== CODE $return_array_product = array_product( $array // array array - The array. ); // Return Values // Returns the product as an integer or float. // // Changelog // Version - Description // 8.3.0 - Now emits E_WARNING when array values cannot be converted to int or float. Previously arrays and objects where ignored whilst every other value was cast to int. Moreover, objects that define a numeric cast (e.g. GMP) are now cast instead of ignored. // // [examples] // Examples // [example] // Example #1 array_product() examples // [php] // // $a = array(2, 4, 6, 8); // echo "product(a) = " . array_product($a) . "\n"; // echo "product(array()) = " . array_product(array()) . "\n"; // // [/php] // The above example will output: // [result] // product(a) = 384 // product(array()) = 1 // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-21) // URL: https://www.php.net/manual/en/function.array-product.php // ========== ARRAY_PRODUCT - END // SYNTAX: // int|float array_product(array $array) return $return_array_product; // int|float } */ // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_PRODUCT // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_PUSH // ============================== PUBLIC // ============================== ABOUT // Push one or more elements onto the end of array. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_push() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array_push(& $array, $values) { $return_array_push = 0; // ========== ARRAY_PUSH - BEGIN // ===== ABOUT // Push one or more elements onto the end of array // ===== DESCRIPTION // array_push() treats array as a stack, and pushes the passed variables onto the end of array. The length of array increases by the number of variables pushed. Has the same effect as: // [php] // $array[] = $var; // [/php] // repeated for each passed value. // Note: If you use array_push() to add one element to the array, it's better to use $array[] = because in that way there is no overhead of calling a function. // Note: array_push() will raise a warning if the first argument is not an array. This differed from the $var[] behaviour where a new array was created, prior to PHP 7.1.0. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_push(array &$array, mixed ...$values): int // ===== CODE $return_array_push = array_push( $array, // array& array - The input array. $values // mixed values - The values to push onto the end of the array. ); // Return Values // Returns the new number of elements in the array. // // Changelog // Version - Description // 7.3.0 - This function can now be called with only one parameter. Formerly, at least two parameters have been required. // // [examples] // Examples // [example] // Example #1 array_push() example // [php] // $stack = array("orange", "banana"); // array_push($stack, "apple", "raspberry"); // print_r($stack); // [/php] // The above example will output: // [result] // Array // ( // [0] => orange // [1] => banana // [2] => apple // [3] => raspberry // ) // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-21) // URL: https://www.php.net/manual/en/function.array-push.php // ========== ARRAY_PUSH - END // SYNTAX: // int array_push(array& $array, mixed $values) return $return_array_push; // int } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_PUSH // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_RAND // ============================== PUBLIC // ============================== ABOUT // Pick one or more random keys out of an array. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_rand() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array_rand($array, $num = 1) { $return_array_rand = null; // ========== ARRAY_RAND - BEGIN // ===== ABOUT // Pick one or more random keys out of an array // ===== DESCRIPTION // Picks one or more random entries out of an array, and returns the key (or keys) of the random entries. // Caution: This function does not generate cryptographically secure values, and must not be used for cryptographic purposes, or purposes that require returned values to be unguessable. // If cryptographically secure randomness is required, the Random\Randomizer may be used with the Random\Engine\Secure engine. For simple use cases, the random_int() and random_bytes() functions provide a convenient and secure API that is backed by the operating system’s CSPRNG. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_rand(array $array, int $num = 1): int|string|array // ===== CODE $return_array_rand = array_rand( $array, // array array - The input array. $num // int num - Specifies how many entries should be picked. ); // Return Values // When picking only one entry, array_rand() returns the key for a random entry. Otherwise, an array of keys for the random entries is returned. This is done so that random keys can be picked from the array as well as random values. If multiple keys are returned, they will be returned in the order they were present in the original array. Trying to pick more elements than there are in the array will result in an E_WARNING level error, and NULL will be returned. // // Changelog // Version - Description // 7.1.0 - The internal randomization algorithm has been changed to use the > Mersenne Twister Random Number Generator instead of the libc rand function. // // [examples] // Examples // [example] // Example #1 array_rand() example // [php] // $input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank"); // $rand_keys = array_rand($input, 2); // echo $input[$rand_keys[0]] . "\n"; // echo $input[$rand_keys[1]] . "\n"; // [/php] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-21) // URL: https://www.php.net/manual/en/function.array-rand.php // ========== ARRAY_RAND - END // SYNTAX: // int|string|array array_rand(array $array, int $num = 1) return $return_array_rand; // int|string|array } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_RAND // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_REDUCE // ============================== PUBLIC // ============================== ABOUT // Iteratively reduce the array to a single value using a callback function. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_reduce() - PHP_4 >= PHP_4_0_5, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array_reduce($array, $callback, $initial = null) { $return_array_reduce = null; // ========== ARRAY_REDUCE - BEGIN // ===== ABOUT // Iteratively reduce the array to a single value using a callback function // ===== DESCRIPTION // array_reduce() applies iteratively the callback function to the elements of the array, so as to reduce the array to a single value. // ===== SUPPORTED // PHP_4 >= PHP_4_0_5, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_reduce(array $array, callable $callback, mixed $initial = null): mixed // ===== CODE $return_array_reduce = array_reduce( $array, // array array - The input array. $callback, // callable callback // callback(mixed $carry, mixed $item): mixed // mixed $carry - Holds the return value of the previous iteration; in the case of the first iteration it instead holds the value of initial. // mixed $item - Holds the value of the current iteration. $initial // mixed initial - If the optional initial is available, it will be used at the beginning of the process, or as a final result in case the array is empty. ); // Return Values // Returns the resulting value. // If the array is empty and initial is not passed, array_reduce() returns null. // // Changelog // Version - Description // 8.0.0 - If callback expects a parameter to be passed by reference, this function will now emit an E_WARNING. // // [examples] // Examples // [example] // Example #1 array_reduce() example // [php] // function sum($carry, $item) // { // $carry += $item; // return $carry; // } // // function product($carry, $item) // { // $carry *= $item; // return $carry; // } // // $a = array(1, 2, 3, 4, 5); // $x = array(); // // var_dump(array_reduce($a, "sum")); // int(15) // var_dump(array_reduce($a, "product", 10)); // int(1200), because: 10*1*2*3*4*5 // var_dump(array_reduce($x, "sum", "No data to reduce")); // string(17) "No data to reduce" // [/php] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-19) // URL: https://www.php.net/manual/en/function.array-reduce.php // ========== ARRAY_REDUCE - END // SYNTAX: // mixed array_reduce(array $array, callable $callback, mixed $initial = null) return $return_array_reduce; // mixed } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_REDUCE // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_REPLACE_RECURSIVE // ============================== OFFLINE // ============================== ABOUT // Replaces elements from passed arrays into the first array recursively. // ============================== SUPPORT // PHP_5 - PHP_8 // ============================== USING FUNCTIONS (1) // array_replace_recursive() - PHP_5 >= PHP_5_3_0, PHP_7, PHP_8 // ============================== CODE /* function php_variable_array_array_replace_recursive($array, $replacements) { $return_array_replace_recursive = null; // ========== ARRAY_REPLACE_RECURSIVE - BEGIN // ===== ABOUT // Replaces elements from passed arrays into the first array recursively // ===== DESCRIPTION // array_replace_recursive() replaces the values of array with the same values from all the following arrays. If a key from the first array exists in the second array, its value will be replaced by the value from the second array. If the key exists in the second array, and not the first, it will be created in the first array. If a key only exists in the first array, it will be left as is. If several arrays are passed for replacement, they will be processed in order, the later array overwriting the previous values. // array_replace_recursive() is recursive : it will recurse into arrays and apply the same process to the inner value. // When the value in the first array is scalar, it will be replaced by the value in the second array, may it be scalar or array. When the value in the first array and the second array are both arrays, array_replace_recursive() will replace their respective value recursively. // ===== SUPPORTED // PHP_5 >= PHP_5_3_0, PHP_7, PHP_8 // ===== SYNTAX // array_replace_recursive(array $array, array ...$replacements): array // ===== CODE $return_array_replace_recursive = array_replace_recursive( $array, // array array - The array in which elements are replaced. $replacements // array replacements - Arrays from which elements will be extracted. ); // Return Values // Returns an array. // // [examples] // Examples // [example] // Example #1 array_replace_recursive() example // [php] // $base = array('citrus' => array( "orange") , 'berries' => array("blackberry", "raspberry"), ); // $replacements = array('citrus' => array('pineapple'), 'berries' => array('blueberry')); // // $basket = array_replace_recursive($base, $replacements); // print_r($basket); // // $basket = array_replace($base, $replacements); // print_r($basket); // [/php] // The above example will output: // [result] // Array // ( // [citrus] => Array // ( // [0] => pineapple // ) // // [berries] => Array // ( // [0] => blueberry // [1] => raspberry // ) // // ) // Array // ( // [citrus] => Array // ( // [0] => pineapple // ) // // [berries] => Array // ( // [0] => blueberry // ) // // ) // [/result] // [/example] // [example] // Example #2 array_replace_recursive() and recursive behavior // [php] // $base = array('citrus' => array("orange") , 'berries' => array("blackberry", "raspberry"), 'others' => 'banana' ); // $replacements = array('citrus' => 'pineapple', 'berries' => array('blueberry'), 'others' => array('litchis')); // $replacements2 = array('citrus' => array('pineapple'), 'berries' => array('blueberry'), 'others' => 'litchis'); // // $basket = array_replace_recursive($base, $replacements, $replacements2); // print_r($basket); // // [/php] // The above example will output: // [result] // Array // ( // [citrus] => Array // ( // [0] => pineapple // ) // // [berries] => Array // ( // [0] => blueberry // [1] => raspberry // ) // // [others] => litchis // ) // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-21) // URL: https://www.php.net/manual/en/function.array-replace-recursive.php // ========== ARRAY_REPLACE_RECURSIVE - END // SYNTAX: // array array_replace_recursive(array $array, array $replacements) return $return_array_replace_recursive; // array } */ // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_REPLACE_RECURSIVE // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_REPLACE // ============================== OFFLINE // ============================== ABOUT // Replaces elements from passed arrays into the first array. // ============================== SUPPORT // PHP_5 - PHP_8 // ============================== USING FUNCTIONS (1) // array_replace() - PHP_5 >= PHP_5_3_0, PHP_7, PHP_8 // ============================== CODE /* function php_variable_array_array_replace($array, $replacements) { $return_array_replace = null; // ========== ARRAY_REPLACE - BEGIN // ===== ABOUT // Replaces elements from passed arrays into the first array // ===== DESCRIPTION // array_replace() replaces the values of array with values having the same keys in each of the following arrays. If a key from the first array exists in the second array, its value will be replaced by the value from the second array. If the key exists in the second array, and not the first, it will be created in the first array. If a key only exists in the first array, it will be left as is. If several arrays are passed for replacement, they will be processed in order, the later arrays overwriting the previous values. // array_replace() is not recursive : it will replace values in the first array by whatever type is in the second array. // ===== SUPPORTED // PHP_5 >= PHP_5_3_0, PHP_7, PHP_8 // ===== SYNTAX // array_replace(array $array, array ...$replacements): array // ===== CODE $return_array_replace = array_replace( $array, // array array - The array in which elements are replaced. $replacements // array replacements - Arrays from which elements will be extracted. Values from later arrays overwrite the previous values. ); // Return Values // Returns an array. // // [examples] // Examples // [example] // Example #1 array_replace() example // [php] // $base = array("orange", "banana", "apple", "raspberry"); // $replacements = array(0 => "pineapple", 4 => "cherry"); // $replacements2 = array(0 => "grape"); // // $basket = array_replace($base, $replacements, $replacements2); // print_r($basket); // [/php] // The above example will output: // [result] // Array // ( // [0] => grape // [1] => banana // [2] => apple // [3] => raspberry // [4] => cherry // ) // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-21) // URL: https://www.php.net/manual/en/function.array-replace.php // ========== ARRAY_REPLACE - END // SYNTAX: // array array_replace(array $array, array $replacements) return $return_array_replace; // array } */ // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_REPLACE // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_REVERSE // ============================== PUBLIC // ============================== ABOUT // Return an array with elements in reverse order. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_reverse() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array_reverse($array, $preserve_keys = false) { $return_array_reverse = null; // ========== ARRAY_REVERSE - BEGIN // ===== ABOUT // Return an array with elements in reverse order // ===== DESCRIPTION // Takes an input array and returns a new array with the order of the elements reversed. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_reverse(array $array, bool $preserve_keys = false): array // ===== CODE $return_array_reverse = array_reverse( $array, // array array - The input array. $preserve_keys // bool preserve_keys - If set to true numeric keys are preserved. Non-numeric keys are not affected by this setting and will always be preserved. ); // Return Values // Returns the reversed array. // // [examples] // Examples // [example] // Example #1 array_reverse() example // [php] // $input = array("php", 4.0, array("green", "red")); // $reversed = array_reverse($input); // $preserved = array_reverse($input, true); // // print_r($input); // print_r($reversed); // print_r($preserved); // [/php] // The above example will output: // [result] // Array // ( // [0] => php // [1] => 4 // [2] => Array // ( // [0] => green // [1] => red // ) // // ) // Array // ( // [0] => Array // ( // [0] => green // [1] => red // ) // // [1] => 4 // [2] => php // ) // Array // ( // [2] => Array // ( // [0] => green // [1] => red // ) // // [1] => 4 // [0] => php // ) // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-21) // URL: https://www.php.net/manual/en/function.array-reverse.php // ========== ARRAY_REVERSE - END // SYNTAX: // array array_reverse(array $array, bool $preserve_keys = false) return $return_array_reverse; // array } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_REVERSE // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_SEARCH // ============================== PUBLIC // ============================== ABOUT // Searches the array for a given value and returns the first corresponding key if successful. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_search() - PHP_4 >= PHP_4_0_5, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array_search($needle, $haystack, $strict = false) { $return_array_search = false; // ========== ARRAY_SEARCH - BEGIN // ===== ABOUT // Searches the array for a given value and returns the first corresponding key if successful // ===== DESCRIPTION // Searches for needle in haystack. // ===== SUPPORTED // PHP_4 >= PHP_4_0_5, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_search(mixed $needle, array $haystack, bool $strict = false): int|string|false // ===== CODE $return_array_search = array_search( $needle, // mixed $needle - The searched value. // Note: If needle is a string, the comparison is done in a case-sensitive manner. $haystack, // array $haystack - The array. $strict // bool $strict - If the third parameter strict is set to true then the array_search() function will search for identical elements in the haystack. This means it will also perform a strict type comparison of the needle in the haystack, and objects must be the same instance. ); // Return Values // Returns the key for needle if it is found in the array, false otherwise. // If needle is found in haystack more than once, the first matching key is returned. To return the keys for all matching values, use array_keys() with the optional search_value parameter instead. // Warning: This function may return Boolean false, but may also return a non-Boolean value which evaluates to false. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function. // // [examples] // Examples // [example] // Example #1 array_search() example // [php] // $array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red'); // // $key = array_search('green', $array); // $key = 2; // $key = array_search('red', $array); // $key = 1; // [/php] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-19) // URL: https://www.php.net/manual/en/function.array-search.php // ========== ARRAY_SEARCH - END // SYNTAX: // int|string|false array_search(mixed $needle, array $haystack, bool $strict = false) return $return_array_search; // int|string|false } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_SEARCH // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_SHIFT // ============================== PUBLIC // ============================== ABOUT // Shift an element off the beginning of array. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_shift() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array_shift(& $array) { $return_array_shift = null; // ========== ARRAY_SHIFT - BEGIN // ===== ABOUT // Shift an element off the beginning of array // ===== DESCRIPTION // array_shift() shifts the first value of the array off and returns it, shortening the array by one element and moving everything down. All numerical array keys will be modified to start counting from zero while literal keys won't be affected. // Note: This function will reset() the array pointer of the input array after use. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_shift(array &$array): mixed // ===== CODE $return_array_shift = array_shift( $array // array& array - The input array. ); // Return Values // Returns the shifted value, or null if array is empty or is not an array. // // [examples] // Examples // [example] // Example #1 array_shift() example // [php] // $stack = array("orange", "banana", "apple", "raspberry"); // $fruit = array_shift($stack); // print_r($stack); // [/php] // The above example will output: // [result] // Array // ( // [0] => banana // [1] => apple // [2] => raspberry // ) // [/result] // and orange will be assigned to $fruit. // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-21) // URL: https://www.php.net/manual/en/function.array-shift.php // ========== ARRAY_SHIFT - END // SYNTAX: // mixed array_shift(array& $array) return $return_array_shift; // mixed } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_SHIFT // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_SLICE // ============================== PUBLIC // ============================== ABOUT // Extract a slice of the array. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_slice() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array_slice($array, $offset, $length = null, $preserve_keys = false) { $return_array_slice = null; // ========== ARRAY_SLICE - BEGIN // ===== ABOUT // Extract a slice of the array // ===== DESCRIPTION // array_slice() returns the sequence of elements from the array array as specified by the offset and length parameters. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_slice( // array $array, // int $offset, // ?int $length = null, // bool $preserve_keys = false // ): array // ===== CODE $return_array_slice = array_slice( $array, // array array - The input array. $offset, // int offset - If offset is non-negative, the sequence will start at that offset in the array. // If offset is negative, the sequence will start that far from the end of the array. // Note: The offset parameter denotes the position in the array, not the key. $length, // int length - If length is given and is positive, then the sequence will have up to that many elements in it. // If the array is shorter than the length, then only the available array elements will be present. // If length is given and is negative then the sequence will stop that many elements from the end of the array. // If it is omitted, then the sequence will have everything from offset up until the end of the array. $preserve_keys // bool preserve_keys - // Note: array_slice() will reorder and reset the integer array indices by default. This behaviour can be changed by setting preserve_keys to true. String keys are always preserved, regardless of this parameter. ); // Return Values // Returns the slice. If the offset is larger than the size of the array, an empty array is returned. // // [examples] // Examples // [example] // Example #1 array_slice() examples // [php] // $input = array("a", "b", "c", "d", "e"); // // $output = array_slice($input, 2); // returns "c", "d", and "e" // $output = array_slice($input, -2, 1); // returns "d" // $output = array_slice($input, 0, 3); // returns "a", "b", and "c" // // // note the differences in the array keys // print_r(array_slice($input, 2, -1)); // print_r(array_slice($input, 2, -1, true)); // [/php] // The above example will output: // [result] // Array // ( // [0] => c // [1] => d // ) // Array // ( // [2] => c // [3] => d // ) // [/result] // [/example] // [example] // Example #2 array_slice() and one-based array // [php] // $input = array(1 => "a", "b", "c", "d", "e"); // print_r(array_slice($input, 1, 2)); // [/php] // The above example will output: // [result] // Array // ( // [0] => b // [1] => c // ) // [/result] // [/example] // [example] // Example #3 array_slice() and array with mixed keys // [php] // $ar = array('a'=>'apple', 'b'=>'banana', '42'=>'pear', 'd'=>'orange'); // print_r(array_slice($ar, 0, 3)); // print_r(array_slice($ar, 0, 3, true)); // [/php] // The above example will output: // [result] // Array // ( // [a] => apple // [b] => banana // [0] => pear // ) // Array // ( // [a] => apple // [b] => banana // [42] => pear // ) // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-21) // URL: https://www.php.net/manual/en/function.array-slice.php // ========== ARRAY_SLICE - END // SYNTAX: // array array_slice(array $array, int $offset, int $length = null, bool $preserve_keys = false) return $return_array_slice; // array } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_SLICE // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_SPLICE // ============================== PUBLIC // ============================== ABOUT // Remove a portion of the array and replace it with something else. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_splice() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array_splice(& $array, $offset, $length = null, $replacement = array()) { $return_array_splice = null; // ========== ARRAY_SPLICE - BEGIN // ===== ABOUT // Remove a portion of the array and replace it with something else // ===== DESCRIPTION // Removes the elements designated by offset and length from the array array, and replaces them with the elements of the replacement array, if supplied. // Note: Numerical keys in array are not preserved. // Note: If replacement is not an array, it will be typecast to one (i.e. (array) $replacement). This may result in unexpected behavior when using an object or null replacement. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_splice( // array &$array, // int $offset, // ?int $length = null, // mixed $replacement = [] // ): array // ===== CODE $return_array_splice = array_splice( $array, // array& array - The input array. $offset, // int offset - If offset is positive then the start of the removed portion is at that offset from the beginning of the array array. // If offset is negative then the start of the removed portion is at that offset from the end of the array array. $length, // int length - If length is omitted, removes everything from offset to the end of the array. // If length is specified and is positive, then that many elements will be removed. // If length is specified and is negative, then the end of the removed portion will be that many elements from the end of the array. // If length is specified and is zero, no elements will be removed. // Tip: To remove everything from offset to the end of the array when replacement is also specified, use count($input) for length. $replacement // mixed replacement - If replacement array is specified, then the removed elements are replaced with elements from this array. // If offset and length are such that nothing is removed, then the elements from the replacement array are inserted in the place specified by the offset. // Note: Keys in the replacement array are not preserved. // If replacement is just one element it is not necessary to put array() or square brackets around it, unless the element is an array itself, an object or null. ); // Return Values // Returns an array consisting of the extracted elements. // // Changelog // Version - Description // 8.0.0 - length is nullable now. // // [examples] // Examples // [example] // Example #1 array_splice() examples // [php] // $input = array("red", "green", "blue", "yellow"); // array_splice($input, 2); // var_dump($input); // // $input = array("red", "green", "blue", "yellow"); // array_splice($input, 1, -1); // var_dump($input); // // $input = array("red", "green", "blue", "yellow"); // array_splice($input, 1, count($input), "orange"); // var_dump($input); // // $input = array("red", "green", "blue", "yellow"); // array_splice($input, -1, 1, array("black", "maroon")); // var_dump($input); // [/php] // The above example will output: // [result] // array(2) { // [0]=> // string(3) "red" // [1]=> // string(5) "green" // } // array(2) { // [0]=> // string(3) "red" // [1]=> // string(6) "yellow" // } // array(2) { // [0]=> // string(3) "red" // [1]=> // string(6) "orange" // } // array(5) { // [0]=> // string(3) "red" // [1]=> // string(5) "green" // [2]=> // string(4) "blue" // [3]=> // string(5) "black" // [4]=> // string(6) "maroon" // } // [/result] // [/example] // [example] // Example #2 Equivalent statements to various array_splice() examples // The following statements are equivalent: // [php] // // // append two elements to $input // array_push($input, $x, $y); // array_splice($input, count($input), 0, array($x, $y)); // // // remove the last element of $input // array_pop($input); // array_splice($input, -1); // // // remove the first element of $input // array_shift($input); // array_splice($input, 0, 1); // // // insert an element at the start of $input // array_unshift($input, $x, $y); // array_splice($input, 0, 0, array($x, $y)); // // // replace the value in $input at index $x // $input[$x] = $y; // for arrays where key equals offset // array_splice($input, $x, 1, $y); // // [/php] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-21) // URL: https://www.php.net/manual/en/function.array-splice.php // ========== ARRAY_SPLICE - END // SYNTAX: // array array_splice(array& $array, int $offset, int $length = null, mixed $replacement = array()) return $return_array_splice; // array } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_SPLICE // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_SUM // ============================== PUBLIC // ============================== ABOUT // Calculate the sum of values in an array. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_sum() - PHP_4 >= PHP_4_0_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array_sum($array) { $return_array_sum = 0; // ========== ARRAY_SUM - BEGIN // ===== ABOUT // Calculate the sum of values in an array // ===== DESCRIPTION // array_sum() returns the sum of values in an array. // ===== SUPPORTED // PHP_4 >= PHP_4_0_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_sum(array $array): int|float // ===== CODE $return_array_sum = array_sum( $array // array array - The input array. ); // Return Values // Returns the sum of values as an integer or float; 0 if the array is empty. // // Changelog // Version - Description // 8.3.0 - Now emits E_WARNING when array values cannot be converted to int or float. Previously arrays and objects where ignored whilst every other value was cast to int. Moreover, objects that define a numeric cast (e.g. GMP) are now cast instead of ignored. // // [examples] // Examples // [example] // Example #1 array_sum() examples // [php] // $a = array(2, 4, 6, 8); // echo "sum(a) = " . array_sum($a) . "\n"; // // $b = array("a" => 1.2, "b" => 2.3, "c" => 3.4); // echo "sum(b) = " . array_sum($b) . "\n"; // [/php] // The above example will output: // [result] // sum(a) = 20 // sum(b) = 6.9 // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-21) // URL: https://www.php.net/manual/en/function.array-sum.php // ========== ARRAY_SUM - END // SYNTAX: // int|float array_sum(array $array) return $return_array_sum; // int|float } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_SUM // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_UDIFF_ASSOC // ============================== OFFLINE // ============================== ABOUT // Computes the difference of arrays with additional index check, compares data by a callback function. // ============================== SUPPORT // PHP_5 - PHP_8 // ============================== USING FUNCTIONS (1) // array_udiff_assoc() - PHP_5, PHP_7, PHP_8 // ============================== CODE /* function php_variable_array_array_udiff_assoc($array, $arrays, $value_compare_func) { $return_array_udiff_assoc = null; // ========== ARRAY_UDIFF_ASSOC - BEGIN // ===== ABOUT // Computes the difference of arrays with additional index check, compares data by a callback function // ===== DESCRIPTION // Computes the difference of arrays with additional index check, compares data by a callback function. // Note: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_udiff_assoc($array1[0], $array2[0], "some_comparison_func");. // ===== SUPPORTED // PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_udiff_assoc(array $array, array ...$arrays, callable $value_compare_func): array // ===== CODE $return_array_udiff_assoc = array_udiff_assoc( $array, // array array - The first array. $arrays, // array arrays - Arrays to compare against. $value_compare_func // callable value_compare_func - The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. // callback(mixed $a, mixed $b): int // Caution: Returning non-integer values from the comparison function, such as float, will result in an internal cast to int of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal. ); // Return Values // array_udiff_assoc() returns an array containing all the values from array that are not present in any of the other arguments. Note that the keys are used in the comparison unlike array_diff() and array_udiff(). The comparison of arrays' data is performed by using an user-supplied callback. In this aspect the behaviour is opposite to the behaviour of array_diff_assoc() which uses internal function for comparison. // // [examples] // Examples // [example] // Example #1 array_udiff_assoc() example // [php] // class cr { // private $priv_member; // function __construct($val) // { // $this->priv_member = $val; // } // // static function comp_func_cr($a, $b) // { // if ($a->priv_member === $b->priv_member) return 0; // return ($a->priv_member > $b->priv_member)? 1:-1; // } // } // // $a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),); // $b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),); // // $result = array_udiff_assoc($a, $b, array("cr", "comp_func_cr")); // print_r($result); // [/php] // The above example will output: // [result] // Array // ( // [0.1] => cr Object // ( // [priv_member:private] => 9 // ) // // [0.5] => cr Object // ( // [priv_member:private] => 12 // ) // // [0] => cr Object // ( // [priv_member:private] => 23 // ) // ) // [/result] // In our example above you see the "1" => new cr(4) pair is present in both arrays and thus it is not in the output from the function. // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.array-udiff-assoc.php // ========== ARRAY_UDIFF_ASSOC - END // SYNTAX: // array array_udiff_assoc(array $array, array $arrays, callable $value_compare_func) return $return_array_udiff_assoc; // array } */ // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_UDIFF_ASSOC // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_UDIFF_UASSOC // ============================== OFFLINE // ============================== ABOUT // Computes the difference of arrays with additional index check, compares data and indexes by a callback function. // ============================== SUPPORT // PHP_5 - PHP_8 // ============================== USING FUNCTIONS (1) // array_udiff_uassoc() - PHP_5, PHP_7, PHP_8 // ============================== CODE /* function php_variable_array_array_udiff_uassoc($array, $arrays, $value_compare_func, $key_compare_func) { $return_array_udiff_uassoc = null; // ========== ARRAY_UDIFF_UASSOC - BEGIN // ===== ABOUT // Computes the difference of arrays with additional index check, compares data and indexes by a callback function // ===== DESCRIPTION // Computes the difference of arrays with additional index check, compares data and indexes by a callback function. // Note that the keys are used in the comparison unlike array_diff() and array_udiff(). // ===== SUPPORTED // PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_udiff_uassoc( // array $array, // array ...$arrays, // callable $value_compare_func, // callable $key_compare_func // ): array // ===== CODE $return_array_udiff_uassoc = array_udiff_uassoc( $array, // array array - The first array. $arrays, // array arrays - Arrays to compare against. $value_compare_func, // callable value_compare_func - The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. // callback(mixed $a, mixed $b): int // Caution: Returning non-integer values from the comparison function, such as float, will result in an internal cast to int of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal. $key_compare_func // callable key_compare_func - The comparison of keys (indices) is done also by the callback function key_compare_func. This behaviour is unlike what array_udiff_assoc() does, since the latter compares the indices by using an internal function. ); // Return Values // Returns an array containing all the values from array that are not present in any of the other arguments. // // [examples] // Examples // [example] // Example #1 array_udiff_uassoc() example // [php] // class cr { // private $priv_member; // function __construct($val) // { // $this->priv_member = $val; // } // // static function comp_func_cr($a, $b) // { // if ($a->priv_member === $b->priv_member) return 0; // return ($a->priv_member > $b->priv_member)? 1:-1; // } // // static function comp_func_key($a, $b) // { // if ($a === $b) return 0; // return ($a > $b)? 1:-1; // } // } // $a = array("0.1" => new cr(9), "0.5" => new cr(12), 0 => new cr(23), 1=> new cr(4), 2 => new cr(-15),); // $b = array("0.2" => new cr(9), "0.5" => new cr(22), 0 => new cr(3), 1=> new cr(4), 2 => new cr(-15),); // // $result = array_udiff_uassoc($a, $b, array("cr", "comp_func_cr"), array("cr", "comp_func_key")); // print_r($result); // [/php] // The above example will output: // [result] // Array // ( // [0.1] => cr Object // ( // [priv_member:private] => 9 // ) // // [0.5] => cr Object // ( // [priv_member:private] => 12 // ) // // [0] => cr Object // ( // [priv_member:private] => 23 // ) // ) // [/result] // In our example above you see the "1" => new cr(4) pair is present in both arrays and thus it is not in the output from the function. Keep in mind that you have to supply 2 callback functions. // [/example] // [/examples] // // Notes // Note: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using, for example, array_udiff_uassoc($array1[0], $array2[0], "data_compare_func", "key_compare_func");. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.array-udiff-uassoc.php // ========== ARRAY_UDIFF_UASSOC - END // SYNTAX: // array array_udiff_uassoc(array $array, array $arrays, callable $value_compare_func, callable $key_compare_func) return $return_array_udiff_uassoc; // array } */ // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_UDIFF_UASSOC // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_UDIFF // ============================== OFFLINE // ============================== ABOUT // Computes the difference of arrays by using a callback function for data comparison. // ============================== SUPPORT // PHP_5 - PHP_8 // ============================== USING FUNCTIONS (1) // array_udiff() - PHP_5, PHP_7, PHP_8 // ============================== CODE /* function php_variable_array_array_udiff($array, $arrays, $value_compare_func) { $return_array_udiff = null; // ========== ARRAY_UDIFF - BEGIN // ===== ABOUT // Computes the difference of arrays by using a callback function for data comparison // ===== DESCRIPTION // Computes the difference of arrays by using a callback function for data comparison. This is unlike array_diff() which uses an internal function for comparing the data. // ===== SUPPORTED // PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_udiff(array $array, array ...$arrays, callable $value_compare_func): array // ===== CODE $return_array_udiff = array_udiff( $array, // array array - The first array. $arrays, // array arrays - Arrays to compare against. $value_compare_func // callable value_compare_func - The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. // callback(mixed $a, mixed $b): int // Caution: Returning non-integer values from the comparison function, such as float, will result in an internal cast to int of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal. ); // Return Values // Returns an array containing all the values of array that are not present in any of the other arguments. // // [examples] // Examples // [example] // Example #1 array_udiff() example using stdClass Objects // [php] // // Arrays to compare // $array1 = array(new stdClass, new stdClass, // new stdClass, new stdClass, // ); // // $array2 = array( // new stdClass, new stdClass, // ); // // // Set some properties for each object // $array1[0]->width = 11; $array1[0]->height = 3; // $array1[1]->width = 7; $array1[1]->height = 1; // $array1[2]->width = 2; $array1[2]->height = 9; // $array1[3]->width = 5; $array1[3]->height = 7; // // $array2[0]->width = 7; $array2[0]->height = 5; // $array2[1]->width = 9; $array2[1]->height = 2; // // function compare_by_area($a, $b) { // $areaA = $a->width * $a->height; // $areaB = $b->width * $b->height; // // if ($areaA < $areaB) { // return -1; // } elseif ($areaA > $areaB) { // return 1; // } else { // return 0; // } // } // // print_r(array_udiff($array1, $array2, 'compare_by_area')); // [/php] // The above example will output: // [result] // Array // ( // [0] => stdClass Object // ( // [width] => 11 // [height] => 3 // ) // // [1] => stdClass Object // ( // [width] => 7 // [height] => 1 // ) // // ) // [/result] // [/example] // [example] // Example #2 array_udiff() example using DateTime Objects // [php] // class MyCalendar { // public $free = array(); // public $booked = array(); // // public function __construct($week = 'now') { // $start = new DateTime($week); // $start->modify('Monday this week midnight'); // $end = clone $start; // $end->modify('Friday this week midnight'); // $interval = new DateInterval('P1D'); // foreach (new DatePeriod($start, $interval, $end) as $freeTime) { // $this->free[] = $freeTime; // } // } // // public function bookAppointment(DateTime $date, $note) { // $this->booked[] = array('date' => $date->modify('midnight'), 'note' => $note); // } // // public function checkAvailability() { // return array_udiff($this->free, $this->booked, array($this, 'customCompare')); // } // // public function customCompare($free, $booked) { // if (is_array($free)) $a = $free['date']; // else $a = $free; // if (is_array($booked)) $b = $booked['date']; // else $b = $booked; // if ($a == $b) { // return 0; // } elseif ($a > $b) { // return 1; // } else { // return -1; // } // } // } // // // Create a calendar for weekly appointments // $myCalendar = new MyCalendar; // // // Book some appointments for this week // $myCalendar->bookAppointment(new DateTime('Monday this week'), "Cleaning GoogleGuy's apartment."); // $myCalendar->bookAppointment(new DateTime('Wednesday this week'), "Going on a snowboarding trip."); // $myCalendar->bookAppointment(new DateTime('Friday this week'), "Fixing buggy code."); // // // Check availability of days by comparing $booked dates against $free dates // echo "I'm available on the following days this week...\n\n"; // foreach ($myCalendar->checkAvailability() as $free) { // echo $free->format('l'), "\n"; // } // echo "\n\n"; // echo "I'm busy on the following days this week...\n\n"; // foreach ($myCalendar->booked as $booked) { // echo $booked['date']->format('l'), ": ", $booked['note'], "\n"; // } // [/php] // The above example will output: // [result] // I'm available on the following days this week... // // Tuesday // Thursday // // // I'm busy on the following days this week... // // Monday: Cleaning GoogleGuy's apartment. // Wednesday: Going on a snowboarding trip. // Friday: Fixing buggy code. // [/result] // [/example] // [/examples] // // Notes // Note: Please note that this function only checks one dimension of a n-dimensional array. Of course you can check deeper dimensions by using array_udiff($array1[0], $array2[0], "data_compare_func");. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.array-udiff.php // ========== ARRAY_UDIFF - END // SYNTAX: // array array_udiff(array $array, array $arrays, callable $value_compare_func) return $return_array_udiff; // array } */ // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_UDIFF // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_UINTERSECT_ASSOC // ============================== OFFLINE // ============================== ABOUT // Computes the intersection of arrays with additional index check, compares data by a callback function. // ============================== SUPPORT // PHP_5 - PHP_8 // ============================== USING FUNCTIONS (1) // array_uintersect_assoc() - PHP_5, PHP_7, PHP_8 // ============================== CODE /* function php_variable_array_array_uintersect_assoc($array, $arrays, $value_compare_func) { $return_array_uintersect_assoc = null; // ========== ARRAY_UINTERSECT_ASSOC - BEGIN // ===== ABOUT // Computes the intersection of arrays with additional index check, compares data by a callback function // ===== DESCRIPTION // Computes the intersection of arrays with additional index check, compares data by a callback function. // Note that the keys are used in the comparison unlike in array_uintersect(). The data is compared by using a callback function. // ===== SUPPORTED // PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_uintersect_assoc(array $array, array ...$arrays, callable $value_compare_func): array // ===== CODE $return_array_uintersect_assoc = array_uintersect_assoc( $array, // array array - The first array. $arrays, // array arrays - Arrays to compare against. $value_compare_func // callable value_compare_func - The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. // callback(mixed $a, mixed $b): int // Caution: Returning non-integer values from the comparison function, such as float, will result in an internal cast to int of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal. ); // Return Values // Returns an array containing all the values of array that are present in all the arguments. // // [examples] // Examples // [example] // Example #1 array_uintersect_assoc() example // [php] // $array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red"); // $array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red"); // // print_r(array_uintersect_assoc($array1, $array2, "strcasecmp")); // [/php] // The above example will output: // [result] // Array // ( // [a] => green // ) // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.array-uintersect-assoc.php // ========== ARRAY_UINTERSECT_ASSOC - END // SYNTAX: // array array_uintersect_assoc(array $array, array $arrays, callable $value_compare_func) return $return_array_uintersect_assoc; // array } */ // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_UINTERSECT_ASSOC // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_UINTERSECT_UASSOC // ============================== OFFLINE // ============================== ABOUT // Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions. // ============================== SUPPORT // PHP_5 - PHP_8 // ============================== USING FUNCTIONS (1) // array_uintersect_uassoc() - PHP_5, PHP_7, PHP_8 // ============================== CODE /* function php_variable_array_array_uintersect_uassoc($array1, $arrays, $value_compare_func, $key_compare_func) { $return_array_uintersect_uassoc = null; // ========== ARRAY_UINTERSECT_UASSOC - BEGIN // ===== ABOUT // Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions // ===== DESCRIPTION // Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions. // ===== SUPPORTED // PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_uintersect_uassoc( // array $array1, // array ...$arrays, // callable $value_compare_func, // callable $key_compare_func // ): array // ===== CODE $return_array_uintersect_uassoc = array_uintersect_uassoc( $array1, // array array1 - The first array. $arrays, // array arrays - Further arrays. $value_compare_func, // callable value_compare_func - The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. // callback(mixed $a, mixed $b): int // Caution: Returning non-integer values from the comparison function, such as float, will result in an internal cast to int of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal. $key_compare_func // callable key_compare_func - Key comparison callback function. ); // Return Values // Returns an array containing all the values of array1 that are present in all the arguments. // // [examples] // Examples // [example] // Example #1 array_uintersect_uassoc() example // [php] // $array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red"); // $array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red"); // // print_r(array_uintersect_uassoc($array1, $array2, "strcasecmp", "strcasecmp")); // [/php] // The above example will output: // [result] // Array // ( // [a] => green // [b] => brown // ) // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.array-uintersect-uassoc.php // ========== ARRAY_UINTERSECT_UASSOC - END // SYNTAX: // array array_uintersect_uassoc(array $array1, array $arrays, callable $value_compare_func, callable $key_compare_func) return $return_array_uintersect_uassoc; // array } */ // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_UINTERSECT_UASSOC // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_UINTERSECT // ============================== OFFLINE // ============================== ABOUT // Computes the intersection of arrays, compares data by a callback function. // ============================== SUPPORT // PHP_5 - PHP_8 // ============================== USING FUNCTIONS (1) // array_uintersect() - PHP_5, PHP_7, PHP_8 // ============================== CODE /* function php_variable_array_array_uintersect($array, $arrays, $value_compare_func) { $return_array_uintersect = null; // ========== ARRAY_UINTERSECT - BEGIN // ===== ABOUT // Computes the intersection of arrays, compares data by a callback function // ===== DESCRIPTION // Computes the intersection of arrays, compares data by a callback function. // ===== SUPPORTED // PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_uintersect(array $array, array ...$arrays, callable $value_compare_func): array // ===== CODE $return_array_uintersect = array_uintersect( $array, // array array - The first array. $arrays, // array arrays - Arrays to compare against. $value_compare_func // callable value_compare_func - The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. // callback(mixed $a, mixed $b): int // Caution: Returning non-integer values from the comparison function, such as float, will result in an internal cast to int of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal. ); // Return Values // Returns an array containing all the values of array that are present in all the arguments. // // [examples] // Examples // [example] // Example #1 array_uintersect() example // [php] // $array1 = array("a" => "green", "b" => "brown", "c" => "blue", "red"); // $array2 = array("a" => "GREEN", "B" => "brown", "yellow", "red"); // // print_r(array_uintersect($array1, $array2, "strcasecmp")); // [/php] // The above example will output: // [result] // Array // ( // [a] => green // [b] => brown // [0] => red // ) // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.array-uintersect.php // ========== ARRAY_UINTERSECT - END // SYNTAX: // array array_uintersect(array $array, array $arrays, callable $value_compare_func) return $return_array_uintersect; // array } */ // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_UINTERSECT // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_UNIQUE // ============================== PUBLIC // ============================== ABOUT // Removes duplicate values from an array. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_unique() - PHP_4 >= PHP_4_0_1, PHP_5, PHP_7, PHP_8 // ============================== USING CONSTANTS (1) // SORT_STRING - array_unique() // ============================== CODE function php_variable_array_array_unique($array, $flags = SORT_STRING) { $return_array_unique = null; // ========== ARRAY_UNIQUE - BEGIN // ===== ABOUT // Removes duplicate values from an array // ===== DESCRIPTION // Takes an input array and returns a new array without duplicate values. // Note that keys are preserved. If multiple elements compare equal under the given flags, then the key and value of the first equal element will be retained. // Note: Two elements are considered equal if and only if (string) $elem1 === (string) $elem2 i.e. when the string representation is the same, the first element will be used. // ===== SUPPORTED // PHP_4 >= PHP_4_0_1, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_unique(array $array, int $flags = SORT_STRING): array // ===== CODE $return_array_unique = array_unique( $array, // array array - The input array. $flags // int flags - The optional second parameter flags may be used to modify the comparison behavior using these values: // Comparison type flags: // * SORT_REGULAR - compare items normally (don't change types) // * SORT_NUMERIC - compare items numerically // * SORT_STRING - compare items as strings // * SORT_LOCALE_STRING - compare items as strings, based on the current locale. ); // Return Values // Returns the filtered array. // // Changelog // Version - Description // 7.2.0 - If flags is SORT_STRING, formerly array has been copied and non-unique elements have been removed (without packing the array afterwards), but now a new array is built by adding the unique elements. This can result in different numeric indexes. // // [examples] // Examples // [example] // Example #1 array_unique() example // [php] // $input = array("a" => "green", "red", "b" => "green", "blue", "red"); // $result = array_unique($input); // print_r($result); // [/php] // The above example will output: // [result] // Array // ( // [a] => green // [0] => red // [1] => blue // ) // [/result] // [/example] // [example] // Example #2 array_unique() and types // [php] // $input = array(4, "4", "3", 4, 3, "3"); // $result = array_unique($input); // var_dump($result); // [/php] // The above example will output: // [result] // array(2) { // [0] => int(4) // [2] => string(1) "3" // } // [/result] // [/example] // [/examples] // // Notes // Note: Note that array_unique() is not intended to work on multi dimensional arrays. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-19) // URL: https://www.php.net/manual/en/function.array-unique.php // ========== ARRAY_UNIQUE - END // SYNTAX: // array array_unique(array $array, int $flags = SORT_STRING) return $return_array_unique; // array } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_UNIQUE // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_UNSHIFT // ============================== PUBLIC // ============================== ABOUT // Prepend one or more elements to the beginning of an array. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_unshift() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array_unshift(& $array, $values) { $return_array_unshift = 0; // ========== ARRAY_UNSHIFT - BEGIN // ===== ABOUT // Prepend one or more elements to the beginning of an array // ===== DESCRIPTION // array_unshift() prepends passed elements to the front of the array. Note that the list of elements is prepended as a whole, so that the prepended elements stay in the same order. All numerical array keys will be modified to start counting from zero while literal keys won't be changed. // Note: Resets array's internal pointer to the first element. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_unshift(array &$array, mixed ...$values): int // ===== CODE $return_array_unshift = array_unshift( $array, // array& array - The input array. $values // mixed values - The values to prepend. ); // Return Values // Returns the new number of elements in the array. // // Changelog // Version - Description // 7.3.0 - This function can now be called with only one parameter. Formerly, at least two parameters have been required. // // [examples] // Examples // [example] // Example #1 array_unshift() example // [php] // $queue = [ // "orange", // "banana" // ]; // // array_unshift($queue, "apple", "raspberry"); // var_dump($queue); // [/php] // The above example will output: // [result] // array(4) { // [0] => // string(5) "apple" // [1] => // string(9) "raspberry" // [2] => // string(6) "orange" // [3] => // string(6) "banana" // } // [/result] // [/example] // [example] // Example #2 Usage with associative arrays // If one associative array is prepended to another associative array, the prepended array is numerically indexed into the former array. // [php] // $foods = [ // 'apples' => [ // 'McIntosh' => 'red', // 'Granny Smith' => 'green', // ], // 'oranges' => [ // 'Navel' => 'orange', // 'Valencia' => 'orange', // ], // ]; // $vegetables = [ // 'lettuce' => [ // 'Iceberg' => 'green', // 'Butterhead' => 'green', // ], // 'carrots' => [ // 'Deep Purple Hybrid' => 'purple', // 'Imperator' => 'orange', // ], // 'cucumber' => [ // 'Kirby' => 'green', // 'Gherkin' => 'green', // ], // ]; // // array_unshift($foods, $vegetables); // var_dump($foods); // [/php] // The above example will output: // [result] // array(3) { // [0] => // array(3) { // 'lettuce' => // array(2) { // 'Iceberg' => // string(5) "green" // 'Butterhead' => // string(5) "green" // } // 'carrots' => // array(2) { // 'Deep Purple Hybrid' => // string(6) "purple" // 'Imperator' => // string(6) "orange" // } // 'cucumber' => // array(2) { // 'Kirby' => // string(5) "green" // 'Gherkin' => // string(5) "green" // } // } // 'apples' => // array(2) { // 'McIntosh' => // string(3) "red" // 'Granny Smith' => // string(5) "green" // } // 'oranges' => // array(2) { // 'Navel' => // string(6) "orange" // 'Valencia' => // string(6) "orange" // } // } // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-21) // URL: https://www.php.net/manual/en/function.array-unshift.php // ========== ARRAY_UNSHIFT - END // SYNTAX: // int array_unshift(array& $array, mixed $values) return $return_array_unshift; // int } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_UNSHIFT // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_VALUES // ============================== PUBLIC // ============================== ABOUT // Return all the values of an array. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_values() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array_values($array) { $return_array_values = null; // ========== ARRAY_VALUES - BEGIN // ===== ABOUT // Return all the values of an array // ===== DESCRIPTION // array_values() returns all the values from the array and indexes the array numerically. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_values(array $array): array // ===== CODE $return_array_values = array_values( $array // array array - The array. ); // Return Values // Returns an indexed array of values. // // [examples] // Examples // [example] // Example #1 array_values() example // [php] // $array = array("size" => "XL", "color" => "gold"); // print_r(array_values($array)); // [/php] // The above example will output: // [result] // Array // ( // [0] => XL // [1] => gold // ) // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-19) // URL: https://www.php.net/manual/en/function.array-values.php // ========== ARRAY_VALUES - END // SYNTAX: // array array_values(array $array) return $return_array_values; // array } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_VALUES // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_WALK_RECURSIVE // ============================== OFFLINE // ============================== ABOUT // Apply a user function recursively to every member of an array. // ============================== SUPPORT // PHP_5 - PHP_8 // ============================== USING FUNCTIONS (1) // array_walk_recursive() - PHP_5, PHP_7, PHP_8 // ============================== CODE /* function php_variable_array_array_walk_recursive(& $array, $callback, $arg = null) { $return_array_walk_recursive = false; // ========== ARRAY_WALK_RECURSIVE - BEGIN // ===== ABOUT // Apply a user function recursively to every member of an array // ===== DESCRIPTION // Applies the user-defined callback function to each element of the array. This function will recurse into deeper arrays. // ===== SUPPORTED // PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_walk_recursive(array|object &$array, callable $callback, mixed $arg = null): bool // ===== CODE $return_array_walk_recursive = array_walk_recursive( $array, // array|object array - The input array. $callback, // callable callback - Typically, callback takes on two parameters. The array parameter's value being the first, and the key/index second. // Note: If callback needs to be working with the actual values of the array, specify the first parameter of callback as a reference. Then, any changes made to those elements will be made in the original array itself. $arg // mixed arg - If the optional arg parameter is supplied, it will be passed as the third parameter to the callback. ); // Return Values // Returns true on success or false on failure. // // [examples] // Examples // [example] // Example #1 array_walk_recursive() example // [php] // $sweet = array('a' => 'apple', 'b' => 'banana'); // $fruits = array('sweet' => $sweet, 'sour' => 'lemon'); // // function test_print($item, $key) // { // echo "$key holds $item\n"; // } // // array_walk_recursive($fruits, 'test_print'); // [/php] // The above example will output: // [result] // a holds apple // b holds banana // sour holds lemon // [/result] // You may notice that the key 'sweet' is never displayed. Any key that holds an array will not be passed to the function. // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.array-walk-recursive.php // ========== ARRAY_WALK_RECURSIVE - END // SYNTAX: // bool array_walk_recursive(array|object& $array, callable $callback, mixed $arg = null) return $return_array_walk_recursive; // bool } */ // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_WALK_RECURSIVE // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY_WALK // ============================== PUBLIC // ============================== ABOUT // Apply a user supplied function to every member of an array. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array_walk() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array_walk(& $array, $callback, $arg = null) { $return_array_walk = false; // ========== ARRAY_WALK - BEGIN // ===== ABOUT // Apply a user supplied function to every member of an array // ===== DESCRIPTION // Applies the user-defined callback function to each element of the array array. // array_walk() is not affected by the internal array pointer of array. array_walk() will walk through the entire array regardless of pointer position. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_walk(array|object &$array, callable $callback, mixed $arg = null): bool // ===== CODE $return_array_walk = array_walk( $array, // array|object array - The input array. $callback, // callable callback - Typically, callback takes on two parameters. The array parameter's value being the first, and the key/index second. // Note: If callback needs to be working with the actual values of the array, specify the first parameter of callback as a reference. Then, any changes made to those elements will be made in the original array itself. // Note: Many internal functions (for example strtolower()) will throw a warning if more than the expected number of argument are passed in and are not usable directly as a callback. // Only the values of the array may potentially be changed; its structure cannot be altered, i.e., the programmer cannot add, unset or reorder elements. If the callback does not respect this requirement, the behavior of this function is undefined, and unpredictable. $arg // mixed arg - If the optional arg parameter is supplied, it will be passed as the third parameter to the callback. ); // Return Values // Returns true. // // Errors/Exceptions // As of PHP 7.1.0, an ArgumentCountError will be thrown if the callback function requires more than 2 parameters (the value and key of the array member), or more than 3 parameters if the arg is also passed. Previously, in this case an error of level E_WARNING would be generated each time array_walk() calls callback. // // Changelog // Version - Description // 8.0.0 - If callback expects the second or third parameter to be passed by reference, this function will now emit an E_WARNING. // // [examples] // Examples // [example] // Example #1 array_walk() example // [php] // $fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple"); // // function test_alter(&$item1, $key, $prefix) // { // $item1 = "$prefix: $item1"; // } // // function test_print($item2, $key) // { // echo "$key. $item2\n"; // } // // echo "Before ...:\n"; // array_walk($fruits, 'test_print'); // // array_walk($fruits, 'test_alter', 'fruit'); // echo "... and after:\n"; // // array_walk($fruits, 'test_print'); // [/php] // The above example will output: // [result] // Before ...: // d. lemon // a. orange // b. banana // c. apple // ... and after: // d. fruit: lemon // a. fruit: orange // b. fruit: banana // c. fruit: apple // [/result] // [/example] // [example] // Example #2 array_walk() example using anonymous function // [php] // $elements = ['a', 'b', 'c']; // // array_walk($elements, function ($value, $key) { // echo "{$key} => {$value}\n"; // }); // // [/php] // The above example will output: // [result] // 0 => a // 1 => b // 2 => c // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.array-walk.php // ========== ARRAY_WALK - END // SYNTAX: // bool array_walk(array|object& $array, callable $callback, mixed $arg = null) return $return_array_walk; // bool } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY_WALK // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARRAY // ============================== PUBLIC // ============================== ABOUT // Create an array. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // array() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_array($values) { $return_array = null; // ========== ARRAY - BEGIN // ===== ABOUT // Create an array // ===== DESCRIPTION // Creates an array. Read the section on the array type for more information on what an array is. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array(mixed ...$values): array // ===== CODE $return_array = array( $values // mixed values - Syntax "index => values", separated by commas, define index and values. index may be of type string or integer. When index is omitted, an integer index is automatically generated, starting at 0. If index is an integer, next generated index will be the biggest integer index + 1. Note that when two identical indices are defined, the last overwrites the first. // Having a trailing comma after the last defined array entry, while unusual, is a valid syntax. ); // Return Values // Returns an array of the parameters. The parameters can be given an index with the => operator. Read the section on the array type for more information on what an array is. // // [examples] // Examples // [example] // The following example demonstrates how to create a two-dimensional array, how to specify keys for associative arrays, and how to skip-and-continue numeric indices in normal arrays. // Example #1 array() example // [php] // $fruits = array ( // "fruits" => array("a" => "orange", "b" => "banana", "c" => "apple"), // "numbers" => array(1, 2, 3, 4, 5, 6), // "holes" => array("first", 5 => "second", "third") // ); // [/php] // [/example] // [example] // Example #2 Automatic index with array() // [php] // $array = array(1, 1, 1, 1, 1, 8 => 1, 4 => 1, 19, 3 => 13); // print_r($array); // [/php] // The above example will output: // [result] // Array // ( // [0] => 1 // [1] => 1 // [2] => 1 // [3] => 13 // [4] => 1 // [8] => 1 // [9] => 19 // ) // [/result] // Note that index '3' is defined twice, and keep its final value of 13. Index 4 is defined after index 8, and next generated index (value 19) is 9, since biggest index was 8. // This example creates a 1-based array. // [/example] // [example] // Example #3 1-based index with array() // [php] // $firstquarter = array(1 => 'January', 'February', 'March'); // print_r($firstquarter); // [/php] // The above example will output: // [result] // Array // ( // [1] => January // [2] => February // [3] => March // ) // [/result] // As in Perl, you can access a value from the array inside double quotes. However, with PHP you'll need to enclose your array between curly braces. // [/example] // [example] // Example #4 Accessing an array inside double quotes // [php] // // $foo = array('bar' => 'baz'); // echo "Hello {$foo['bar']}!"; // Hello baz! // // [/php] // [/example] // [/examples] // // Notes // Note: array() is a language construct used to represent literal arrays, and not a regular function. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-21) // URL: https://www.php.net/manual/en/function.array.php // ========== ARRAY - END // SYNTAX: // array array(mixed $values) return $return_array; // array } // ============================== END // PHP_VARIABLE_ARRAY_ARRAY // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ARSORT // ============================== PUBLIC // ============================== ABOUT // Sort an array in descending order and maintain index association. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // arsort() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== USING CONSTANTS (1) // SORT_REGULAR - arsort() // ============================== CODE function php_variable_array_arsort(& $array, $flags = SORT_REGULAR) { $return_arsort = false; // ========== ARSORT - BEGIN // ===== ABOUT // Sort an array in descending order and maintain index association // ===== DESCRIPTION // Sorts array in place in descending order, such that its keys maintain their correlation with the values they are associated with. // This is used mainly when sorting associative arrays where the actual element order is significant. // Note: If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined. // Note: Resets array's internal pointer to the first element. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // arsort(array &$array, int $flags = SORT_REGULAR): true // ===== CODE $return_arsort = arsort( $array, // array array - The input array. $flags // int flags - The optional second parameter flags may be used to modify the sorting behavior using these values: // // Sorting type flags: // * SORT_REGULAR - compare items normally; the details are described in the comparison operators section // * SORT_NUMERIC - compare items numerically // * SORT_STRING - compare items as strings // * SORT_LOCALE_STRING - compare items as strings, based on the current locale. It uses the locale, which can be changed using setlocale() // * SORT_NATURAL - compare items as strings using "natural ordering" like natsort() // * SORT_FLAG_CASE - can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively ); // Return Values // Always returns true. // // Changelog // Version - Description // 8.2.0 - The return type is true now; previously, it was bool. // // [examples] // Examples // [example] // Example #1 arsort() example // [php] // $fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple"); // arsort($fruits); // foreach ($fruits as $key => $val) { // echo "$key = $val\n"; // } // [/php] // The above example will output: // [result] // a = orange // d = lemon // b = banana // c = apple // [/result] // The fruits have been sorted in reverse alphabetical order, and the index associated with each element has been maintained. // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.arsort.php // ========== ARSORT - END // SYNTAX: // bool arsort(array& $array, int $flags = SORT_REGULAR) return $return_arsort; // bool } // ============================== END // PHP_VARIABLE_ARRAY_ARSORT // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_ASORT // ============================== PUBLIC // ============================== ABOUT // Sort an array in ascending order and maintain index association. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // asort() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== USING CONSTANTS (1) // SORT_REGULAR - asort() // ============================== CODE function php_variable_array_asort(& $array, $flags = SORT_REGULAR) { $return_asort = false; // ========== ASORT - BEGIN // ===== ABOUT // Sort an array in ascending order and maintain index association // ===== DESCRIPTION // Sorts array in place in ascending order, such that its keys maintain their correlation with the values they are associated with. // This is used mainly when sorting associative arrays where the actual element order is significant. // Note: If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined. // Note: Resets array's internal pointer to the first element. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // asort(array &$array, int $flags = SORT_REGULAR): true // ===== CODE $return_asort = asort( $array, // array array - The input array. $flags // int flags - The optional second parameter flags may be used to modify the sorting behavior using these values: // // Sorting type flags: // * SORT_REGULAR - compare items normally; the details are described in the comparison operators section // * SORT_NUMERIC - compare items numerically // * SORT_STRING - compare items as strings // * SORT_LOCALE_STRING - compare items as strings, based on the current locale. It uses the locale, which can be changed using setlocale() // * SORT_NATURAL - compare items as strings using "natural ordering" like natsort() // * SORT_FLAG_CASE - can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively ); // Return Values // Always returns true. // // Changelog // Version - Description // 8.2.0 - The return type is true now; previously, it was bool. // // [examples] // Examples // [example] // Example #1 asort() example // [php] // $fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple"); // asort($fruits); // foreach ($fruits as $key => $val) { // echo "$key = $val\n"; // } // [/php] // The above example will output: // [result] // c = apple // b = banana // d = lemon // a = orange // [/result] // The fruits have been sorted in alphabetical order, and the index associated with each element has been maintained. // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.asort.php // ========== ASORT - END // SYNTAX: // bool asort(array& $array, int $flags = SORT_REGULAR) return $return_asort; // bool } // ============================== END // PHP_VARIABLE_ARRAY_ASORT // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_COMPACT // ============================== PUBLIC // ============================== ABOUT // Create array containing variables and their values. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // compact() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_compact($var_name, $var_names) { $return_compact = null; // ========== COMPACT - BEGIN // ===== ABOUT // Create array containing variables and their values // ===== DESCRIPTION // Creates an array containing variables and their values. // For each of these, compact() looks for a variable with that name in the current symbol table and adds it to the output array such that the variable name becomes the key and the contents of the variable become the value for that key. In short, it does the opposite of extract(). // Note: Before PHP 7.3, any strings that are not set will silently be skipped. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // compact(array|string $var_name, array|string ...$var_names): array // ===== CODE $return_compact = compact( $var_name, // array|string var_name $var_names // array|string var_names - compact() takes a variable number of parameters. Each parameter can be either a string containing the name of the variable, or an array of variable names. The array can contain other arrays of variable names inside it; compact() handles it recursively. ); // Return Values // Returns the output array with all the variables added to it. // // Errors/Exceptions // compact() issues an E_WARNING level error if a given string refers to an unset variable. // // Changelog // Version - Description // 8.0.0 - If a given string references an unset variable, an E_WARNING level error is now issued. // 7.3.0 - compact() now issues an E_NOTICE level error if a given string refers to an unset variable. Formerly, such strings have been silently skipped. // // [examples] // Examples // [example] // Example #1 compact() example // [php] // $city = "San Francisco"; // $state = "CA"; // $event = "SIGGRAPH"; // // $location_vars = array("city", "state"); // // $result = compact("event", $location_vars); // print_r($result); // [/php] // The above example will output: // [result] // Array // ( // [event] => SIGGRAPH // [city] => San Francisco // [state] => CA // ) // [/result] // [/example] // [/examples] // // Notes // Note: Gotcha // Because variable variables may not be used with PHP's Superglobal arrays within functions, the Superglobal arrays may not be passed into compact(). // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-21) // URL: https://www.php.net/manual/en/function.compact.php // ========== COMPACT - END // SYNTAX: // array compact(array|string $var_name, array|string $var_names) return $return_compact; // array } // ============================== END // PHP_VARIABLE_ARRAY_COMPACT // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_COUNT // ============================== PUBLIC // ============================== ABOUT // Counts all elements in an array or in a Countable object. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // count() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== USING CONSTANTS (1) // COUNT_NORMAL - count() // ============================== CODE function php_variable_array_count($value, $mode = COUNT_NORMAL) { $return_count = 0; // ========== COUNT - BEGIN // ===== ABOUT // Counts all elements in an array or in a Countable object // ===== DESCRIPTION // Counts all elements in an array when used with an array. When used with an object that implements the Countable interface, it returns the return value of the method Countable::count(). // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // count(Countable|array $value, int $mode = COUNT_NORMAL): int // ===== CODE $return_count = count( $value, // Countable|array value - An array or Countable object. $mode // int mode - If the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array. // Caution: count() can detect recursion to avoid an infinite loop, but will emit an E_WARNING every time it does (in case the array contains itself more than once) and return a count higher than may be expected. ); // Return Values // Returns the number of elements in value. Prior to PHP 8.0.0, if the parameter was neither an array nor an object that implements the Countable interface, 1 would be returned, unless value was null, in which case 0 would be returned. // // Changelog // Version - Description // 8.0.0 - count() will now throw TypeError on invalid countable types passed to the value parameter. // 7.2.0 - count() will now yield a warning on invalid countable types passed to the value parameter. // // [examples] // Examples // [example] // Example #1 count() example // [php] // $a[0] = 1; // $a[1] = 3; // $a[2] = 5; // var_dump(count($a)); // // $b[0] = 7; // $b[5] = 9; // $b[10] = 11; // var_dump(count($b)); // [/php] // The above example will output: // [result] // int(3) // int(3) // [/result] // [/example] // [example] // Example #2 count() non Countable|array example (bad example - don't do this) // [php] // $b[0] = 7; // $b[5] = 9; // $b[10] = 11; // var_dump(count($b)); // // var_dump(count(null)); // // var_dump(count(false)); // [/php] // The above example will output: // [result] // int(3) // int(0) // int(1) // [/result] // Output of the above example in PHP 7.2: // [result] // int(3) // // Warning: count(): Parameter must be an array or an object that implements Countable in … on line 12 // int(0) // // Warning: count(): Parameter must be an array or an object that implements Countable in … on line 14 // int(1) // [/result] // Output of the above example in PHP 8: // [result] // int(3) // // Fatal error: Uncaught TypeError: count(): Argument #1 ($var) must be of type Countable .. on line 12 // [/result] // [/example] // [example] // Example #3 Recursive count() example // [php] // $food = array('fruits' => array('orange', 'banana', 'apple'), // 'veggie' => array('carrot', 'collard', 'pea')); // // // recursive count // var_dump(count($food, COUNT_RECURSIVE)); // // // normal count // var_dump(count($food)); // // [/php] // The above example will output: // [result] // int(8) // int(2) // [/result] // [/example] // [example] // Example #4 Countable object // [php] // class CountOfMethods implements Countable // { // private function someMethod() // { // } // // public function count(): int // { // return count(get_class_methods($this)); // } // } // // $obj = new CountOfMethods(); // var_dump(count($obj)); // [/php] // The above example will output: // [result] // int(2) // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-21) // URL: https://www.php.net/manual/en/function.count.php // ========== COUNT - END // SYNTAX: // int count(Countable|array $value, int $mode = COUNT_NORMAL) return $return_count; // int } // ============================== END // PHP_VARIABLE_ARRAY_COUNT // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_CURRENT // ============================== PUBLIC // ============================== ABOUT // Return the current element in an array. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // current() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_current($array) { $return_current = null; // ========== CURRENT - BEGIN // ===== ABOUT // Return the current element in an array // ===== DESCRIPTION // Every array has an internal pointer to its "current" element, which is initialized to the first element inserted into the array. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // current(array|object $array): mixed // ===== CODE $return_current = current( $array // array|object array - The array. ); // Return Values // The current() function simply returns the value of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, current() returns false. // Warning: This function may return Boolean false, but may also return a non-Boolean value which evaluates to false. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function. // // Changelog // Version - Description // 8.1.0 - Calling this function on objects is deprecated. Either convert the object to an array using get_mangled_object_vars() first, or use the methods provided by a class that implements Iterator, such as ArrayIterator, instead. // 7.4.0 - Instances of SPL classes are now treated like empty objects that have no properties instead of calling the Iterator method with the same name as this function. // // [examples] // Examples // [example] // Example #1 Example use of current() and friends // [php] // $transport = array('foot', 'bike', 'car', 'plane'); // $mode = current($transport); // $mode = 'foot'; // $mode = next($transport); // $mode = 'bike'; // $mode = current($transport); // $mode = 'bike'; // $mode = prev($transport); // $mode = 'foot'; // $mode = end($transport); // $mode = 'plane'; // $mode = current($transport); // $mode = 'plane'; // // $arr = array(); // var_dump(current($arr)); // bool(false) // // $arr = array(array()); // var_dump(current($arr)); // array(0) { } // [/php] // [/example] // [/examples] // // Notes // Note: The results of calling current() on an empty array and on an array, whose internal pointer points beyond the end of the elements, are indistinguishable from a bool false element. To properly traverse an array which may contain false elements, see the foreach control structure. To still use current() and properly check if the value is really an element of the array, the key() of the current() element should be checked to be strictly different from null. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-21) // URL: https://www.php.net/manual/en/function.current.php // ========== CURRENT - END // SYNTAX: // mixed current(array|object $array) return $return_current; // mixed } // ============================== END // PHP_VARIABLE_ARRAY_CURRENT // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_EACH // ============================== OFFLINE // ============================== ABOUT // Return the current key and value pair from an array and advance the array cursor // // Warning: This function has been DEPRECATED as of PHP 7.2.0, and REMOVED as of PHP 8.0.0. Relying on this function is highly discouraged. // ============================== SUPPORT // PHP_4 - PHP_7 // ============================== USING FUNCTIONS (1) // each() - PHP_4, PHP_5, PHP_7 // ============================== CODE /* function php_variable_array_each(& $array) { $return_each = null; // ========== EACH - BEGIN // ===== ABOUT // Return the current key and value pair from an array and advance the array cursor // Warning: This function has been DEPRECATED as of PHP 7.2.0, and REMOVED as of PHP 8.0.0. Relying on this function is highly discouraged. // ===== DESCRIPTION // Return the current key and value pair from an array and advance the array cursor. // After each() has executed, the array cursor will be left on the next element of the array, or past the last element if it hits the end of the array. You have to use reset() if you want to traverse the array again using each. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7 // ===== SYNTAX // each(array|object &$array): array // ===== CODE $return_each = each( $array // array|object& array - The input array. ); // Return Values // Returns the current key and value pair from the array array. This pair is returned in a four-element array, with the keys 0, 1, key, and value. Elements 0 and key contain the key name of the array element, and 1 and value contain the data. // If the internal pointer for the array points past the end of the array contents, each() returns false. // // [examples] // Examples // [example] // Example #1 each() examples // [php] // $foo = array("bob", "fred", "jussi", "jouni", "egon", "marliese"); // $bar = each($foo); // print_r($bar); // [/php] // $bar now contains the following key/value pairs: // [result] // Array // ( // [1] => bob // [value] => bob // [0] => 0 // [key] => 0 // ) // [/result] // // [php] // $foo = array("Robert" => "Bob", "Seppo" => "Sepi"); // $bar = each($foo); // print_r($bar); // [/php] // $bar now contains the following key/value pairs: // [result] // Array // ( // [1] => Bob // [value] => Bob // [0] => Robert // [key] => Robert // ) // [/result] // each() is typically used in conjunction with list() to traverse an array, here's an example: // [/example] // [example] // Example #2 Traversing an array with each() // [php] // $fruit = array('a' => 'apple', 'b' => 'banana', 'c' => 'cranberry'); // // reset($fruit); // while (list($key, $val) = each($fruit)) { // echo "$key => $val\n"; // } // [/php] // The above example will output: // [result] // a => apple // b => banana // c => cranberry // [/result] // Caution: Because assigning an array to another variable resets the original array's pointer, our example above would cause an endless loop had we assigned $fruit to another variable inside the loop. // Warning: each() will also accept objects, but may return unexpected results. It's therefore not recommended to iterate though object properties with each(). // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-21) // URL: https://www.php.net/manual/en/function.each.php // ========== EACH - END // SYNTAX: // array each(array|object& $array) return $return_each; // array } */ // ============================== END // PHP_VARIABLE_ARRAY_EACH // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_END // ============================== PUBLIC // ============================== ABOUT // Set the internal pointer of an array to its last element. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // end() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_end(& $array) { $return_end = null; // ========== END - BEGIN // ===== ABOUT // Set the internal pointer of an array to its last element // ===== DESCRIPTION // end() advances array's internal pointer to the last element, and returns its value. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // end(array|object &$array): mixed // ===== CODE $return_end = end( $array // array|object& array - The array. This array is passed by reference because it is modified by the function. This means you must pass it a real variable and not a function returning an array because only actual variables may be passed by reference. ); // Return Values // Returns the value of the last element or false for empty array. // // Changelog // Version - Description // 8.1.0 - Calling this function on objects is deprecated. Either convert the object to an array using get_mangled_object_vars() first, or use the methods provided by a class that implements Iterator, such as ArrayIterator, instead. // 7.4.0 - Instances of SPL classes are now treated like empty objects that have no properties instead of calling the Iterator method with the same name as this function. // // [examples] // Examples // [example] // Example #1 end() example // [php] // // $fruits = array('apple', 'banana', 'cranberry'); // echo end($fruits); // cranberry // // [/php] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-21) // URL: https://www.php.net/manual/en/function.end.php // ========== END - END // SYNTAX: // mixed end(array|object& $array) return $return_end; // mixed } // ============================== END // PHP_VARIABLE_ARRAY_END // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_EXTRACT // ============================== PUBLIC // ============================== ABOUT // Import variables into the current symbol table from an array // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // extract() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== USING CONSTANTS (1) // EXTR_OVERWRITE - extract() // ============================== CODE function php_variable_array_extract(& $array, $flags = EXTR_OVERWRITE, $prefix = "") { $return_extract = 0; // ========== EXTRACT - BEGIN // ===== ABOUT // Import variables into the current symbol table from an array // ===== DESCRIPTION // Import variables from an array into the current symbol table. // Checks each key to see whether it has a valid variable name. It also checks for collisions with existing variables in the symbol table. // Warning: Do not use extract() on untrusted data, like user input (e.g. $_GET, $_FILES). // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // extract(array &$array, int $flags = EXTR_OVERWRITE, string $prefix = ""): int // ===== CODE $return_extract = extract( $array, // array& array - An associative array. This function treats keys as variable names and values as variable values. For each key/value pair it will create a variable in the current symbol table, subject to flags and prefix parameters. // You must use an associative array; a numerically indexed array will not produce results unless you use EXTR_PREFIX_ALL or EXTR_PREFIX_INVALID. $flags, // int flags - The way invalid/numeric keys and collisions are treated is determined by the extraction flags. It can be one of the following values: // EXTR_OVERWRITE - If there is a collision, overwrite the existing variable. // EXTR_SKIP - If there is a collision, don't overwrite the existing variable. // EXTR_PREFIX_SAME - If there is a collision, prefix the variable name with prefix. // EXTR_PREFIX_ALL - Prefix all variable names with prefix. // EXTR_PREFIX_INVALID - Only prefix invalid/numeric variable names with prefix. // EXTR_IF_EXISTS - Only overwrite the variable if it already exists in the current symbol table, otherwise do nothing. This is useful for defining a list of valid variables and then extracting only those variables you have defined out of $_REQUEST, for example. // EXTR_PREFIX_IF_EXISTS - Only create prefixed variable names if the non-prefixed version of the same variable exists in the current symbol table. // EXTR_REFS - Extracts variables as references. This effectively means that the values of the imported variables are still referencing the values of the array parameter. You can use this flag on its own or combine it with any other flag by OR'ing the flags. // If flags is not specified, it is assumed to be EXTR_OVERWRITE. $prefix // string prefix - Note that prefix is only required if flags is EXTR_PREFIX_SAME, EXTR_PREFIX_ALL, EXTR_PREFIX_INVALID or EXTR_PREFIX_IF_EXISTS. If the prefixed result is not a valid variable name, it is not imported into the symbol table. Prefixes are automatically separated from the array key by an underscore character. ); // Return Values // Returns the number of variables successfully imported into the symbol table. // // [examples] // Examples // [example] // Example #1 extract() example // A possible use for extract() is to import into the symbol table variables contained in an associative array returned by wddx_deserialize(). // [php] // // /* Suppose that $var_array is an array returned from // wddx_deserialize */ // // $size = "large"; // $var_array = array("color" => "blue", // "size" => "medium", // "shape" => "sphere"); // extract($var_array, EXTR_PREFIX_SAME, "wddx"); // // echo "$color, $size, $shape, $wddx_size\n"; // // [/php] // The above example will output: // [result] // blue, large, sphere, medium // [/result] // The $size wasn't overwritten because we specified EXTR_PREFIX_SAME, which resulted in $wddx_size being created. If EXTR_SKIP was specified, then $wddx_size wouldn't even have been created. EXTR_OVERWRITE would have caused $size to have value "medium", and EXTR_PREFIX_ALL would result in new variables being named $wddx_color, $wddx_size, and $wddx_shape. // [/example] // [/examples] // // Notes // Warning: Do not use extract() on untrusted data, like user input (i.e. $_GET, $_FILES, etc.). If you do, make sure you use one of the non-overwriting flags values such as EXTR_SKIP and be aware that you should extract in the same order that's defined in variables_order within the php.ini. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-21) // URL: https://www.php.net/manual/en/function.extract.php // ========== EXTRACT - END // SYNTAX: // int extract(array& $array, int $flags = EXTR_OVERWRITE, string $prefix = "") return $return_extract; // int } // ============================== END // PHP_VARIABLE_ARRAY_EXTRACT // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_IN_ARRAY // ============================== PUBLIC // ============================== ABOUT // Checks if a value exists in an array. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // in_array() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_in_array($needle, $haystack, $strict = false) { $return_in_array = false; // ========== IN_ARRAY - BEGIN // ===== ABOUT // Checks if a value exists in an array // ===== DESCRIPTION // Searches for needle in haystack using loose comparison unless strict is set. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // in_array(mixed $needle, array $haystack, bool $strict = false): bool // ===== CODE $return_in_array = in_array( $needle, // mixed needle - The searched value. // Note: If needle is a string, the comparison is done in a case-sensitive manner. $haystack, // array haystack - The array. $strict // bool strict - If the third parameter strict is set to true then the in_array() function will also check the types of the needle in the haystack. // Note: Prior to PHP 8.0.0, a string needle will match an array value of 0 in non-strict mode, and vice versa. That may lead to undesireable results. Similar edge cases exist for other types, as well. If not absolutely certain of the types of values involved, always use the strict flag to avoid unexpected behavior. ); // Return Values // Returns true if needle is found in the array, false otherwise. // // [examples] // Examples // [example] // Example #1 in_array() example // [php] // $os = array("Mac", "NT", "Irix", "Linux"); // if (in_array("Irix", $os)) { // echo "Got Irix"; // } // if (in_array("mac", $os)) { // echo "Got mac"; // } // [/php] // The second condition fails because in_array() is case-sensitive, so the program above will display: // [result] // Got Irix // [/result] // [/example] // [example] // Example #2 in_array() with strict example // [php] // $a = array('1.10', 12.4, 1.13); // // if (in_array('12.4', $a, true)) { // echo "'12.4' found with strict check\n"; // } // // if (in_array(1.13, $a, true)) { // echo "1.13 found with strict check\n"; // } // [/php] // The above example will output: // [result] // 1.13 found with strict check // [/result] // [/example] // [example] // Example #3 in_array() with an array as needle // [php] // $a = array(array('p', 'h'), array('p', 'r'), 'o'); // // if (in_array(array('p', 'h'), $a)) { // echo "'ph' was found\n"; // } // // if (in_array(array('f', 'i'), $a)) { // echo "'fi' was found\n"; // } // // if (in_array('o', $a)) { // echo "'o' was found\n"; // } // [/php] // The above example will output: // [result] // 'ph' was found // 'o' was found // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-19) // URL: https://www.php.net/manual/en/function.in-array.php // ========== IN_ARRAY - END // SYNTAX: // bool in_array(mixed $needle, array $haystack, bool $strict = false) return $return_in_array; // bool } // ============================== END // PHP_VARIABLE_ARRAY_IN_ARRAY // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_KEY_EXISTS // ============================== PUBLIC // ============================== ABOUT // Checks if the given key or index exists in the array. // // key_exists - Alias of array_key_exists() // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // key_exists() - PHP_4 >= PHP_4_0_6, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_key_exists($key, $array) { $return_key_exists = false; // ========== KEY_EXISTS - BEGIN // ===== ABOUT // key_exists - Alias of array_key_exists() // ===== DESCRIPTION // This function is an alias of: array_key_exists(). // ===== SUPPORTED // PHP_4 >= PHP_4_0_6, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // ===== CODE $return_key_exists = key_exists( $key, // string|int $key $array // array $array ); // Return // bool // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-19) // URL: https://www.php.net/manual/en/function.key-exists.php // ========== KEY_EXISTS - END // ========== ARRAY_KEY_EXISTS - BEGIN // ===== ABOUT // Checks if the given key or index exists in the array // ===== DESCRIPTION // array_key_exists() returns true if the given key is set in the array. key can be any value possible for an array index. // ===== SUPPORTED // PHP_4 >= PHP_4_0_7, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // array_key_exists(string|int $key, array $array): bool // ===== CODE // $return_array_key_exists = array_key_exists( // // $key, // string|int $key - Value to check. // // $array // array $array - An array with keys to check. // // ); // Return Values // Returns true on success or false on failure. // Note: array_key_exists() will search for the keys in the first dimension only. Nested keys in multidimensional arrays will not be found. // // [examples] // Examples // [example] // Example #1 array_key_exists() example // [php] // $search_array = array('first' => 1, 'second' => 4); // if (array_key_exists('first', $search_array)) { // echo "The 'first' element is in the array"; // } // [/php] // [/example] // [example] // Example #2 array_key_exists() vs isset() // isset() does not return true for array keys that correspond to a null value, while array_key_exists() does. // [php] // $search_array = array('first' => null, 'second' => 4); // // // returns false // isset($search_array['first']); // // // returns true // array_key_exists('first', $search_array); // [/php] // [/example] // [/examples] // // Notes // Note: // For backward compatibility reasons, array_key_exists() will also return true if key is a property defined within an object given as array. This behaviour is deprecated as of PHP 7.4.0, and removed as of PHP 8.0.0. // To check whether a property exists in an object, property_exists() should be used. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-19) // URL: https://www.php.net/manual/en/function.array-key-exists.php // ========== ARRAY_KEY_EXISTS - END // SYNTAX: // bool key_exists(string|int $key, array $array) return $return_key_exists; // bool } // ============================== END // PHP_VARIABLE_ARRAY_KEY_EXISTS // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_KEY // ============================== PUBLIC // ============================== ABOUT // Fetch a key from an array. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // key() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_key($array) { $return_key = null; // ========== KEY - BEGIN // ===== ABOUT // Fetch a key from an array // ===== DESCRIPTION // key() returns the index element of the current array position. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // key(array|object $array): int|string|null // ===== CODE $return_key = key( $array // array|object array - The array. ); // Return Values // The key() function simply returns the key of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, key() returns null. // // Changelog // Version - Description // 8.1.0 - Calling this function on objects is deprecated. Either convert the object to an array using get_mangled_object_vars() first, or use the methods provided by a class that implements Iterator, such as ArrayIterator, instead. // 7.4.0 - Instances of SPL classes are now treated like empty objects that have no properties instead of calling the Iterator method with the same name as this function. // // [examples] // Examples // [example] // Example #1 key() example // [php] // $array = array( // 'fruit1' => 'apple', // 'fruit2' => 'orange', // 'fruit3' => 'grape', // 'fruit4' => 'apple', // 'fruit5' => 'apple'); // // // this cycle echoes all associative array // // key where value equals "apple" // while ($fruit_name = current($array)) { // if ($fruit_name == 'apple') { // echo key($array), "\n"; // } // next($array); // } // [/php] // The above example will output: // [result] // fruit1 // fruit4 // fruit5 // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-19) // URL: https://www.php.net/manual/en/function.key.php // ========== KEY - END // SYNTAX: // int|string|null key(array|object $array) return $return_key; // int|string|null } // ============================== END // PHP_VARIABLE_ARRAY_KEY // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_KRSORT // ============================== PUBLIC // ============================== ABOUT // Sort an array by key in descending order. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // krsort() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== USING CONSTANTS (1) // SORT_REGULAR - krsort() // ============================== CODE function php_variable_array_krsort(& $array, $flags = SORT_REGULAR) { $return_krsort = false; // ========== KRSORT - BEGIN // ===== ABOUT // Sort an array by key in descending order // ===== DESCRIPTION // Sorts array in place by keys in descending order. // Note: If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined. // Note: Resets array's internal pointer to the first element. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // krsort(array &$array, int $flags = SORT_REGULAR): true // ===== CODE $return_krsort = krsort( $array, // array array - The input array. $flags // int flags - The optional second parameter flags may be used to modify the sorting behavior using these values: // // Sorting type flags: // * SORT_REGULAR - compare items normally; the details are described in the comparison operators section // * SORT_NUMERIC - compare items numerically // * SORT_STRING - compare items as strings // * SORT_LOCALE_STRING - compare items as strings, based on the current locale. It uses the locale, which can be changed using setlocale() // * SORT_NATURAL - compare items as strings using "natural ordering" like natsort() // * SORT_FLAG_CASE - can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively ); // Return Values // Always returns true. // // Changelog // Version - Description // 8.2.0 - The return type is true now; previously, it was bool. // // [examples] // Examples // [example] // Example #1 krsort() example // [php] // $fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple"); // krsort($fruits); // foreach ($fruits as $key => $val) { // echo "$key = $val\n"; // } // [/php] // The above example will output: // [result] // d = lemon // c = apple // b = banana // a = orange // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.krsort.php // ========== KRSORT - END // SYNTAX: // bool krsort(array& $array, int $flags = SORT_REGULAR) return $return_krsort; // bool } // ============================== END // PHP_VARIABLE_ARRAY_KRSORT // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_KSORT // ============================== PUBLIC // ============================== ABOUT // Sort an array by key in ascending order. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // ksort() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== USING CONSTANTS (1) // SORT_REGULAR - ksort() // ============================== CODE function php_variable_array_ksort(& $array, $flags = SORT_REGULAR) { $return_ksort = false; // ========== KSORT - BEGIN // ===== ABOUT // Sort an array by key in ascending order // ===== DESCRIPTION // Sorts array in place by keys in ascending order. // Note: If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined. // Note: Resets array's internal pointer to the first element. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // ksort(array &$array, int $flags = SORT_REGULAR): true // ===== CODE $return_ksort = ksort( $array, // array array - The input array. $flags // int flags - The optional second parameter flags may be used to modify the sorting behavior using these values: // // Sorting type flags: // * SORT_REGULAR - compare items normally; the details are described in the comparison operators section // * SORT_NUMERIC - compare items numerically // * SORT_STRING - compare items as strings // * SORT_LOCALE_STRING - compare items as strings, based on the current locale. It uses the locale, which can be changed using setlocale() // * SORT_NATURAL - compare items as strings using "natural ordering" like natsort() // * SORT_FLAG_CASE - can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively ); // Return Values // Always returns true. // // Changelog // Version - Description // 8.2.0 - The return type is true now; previously, it was bool. // // [examples] // Examples // [example] // Example #1 ksort() example // [php] // $fruits = array("d"=>"lemon", "a"=>"orange", "b"=>"banana", "c"=>"apple"); // ksort($fruits); // foreach ($fruits as $key => $val) { // echo "$key = $val\n"; // } // [/php] // The above example will output: // [result] // a = orange // b = banana // c = apple // d = lemon // [/result] // [/example] // [example] // Example #2 ksort() with int keys // [php] // $a = [0 => 'First', 2 => 'Last', 1 => 'Middle']; // var_dump($a); // ksort($a); // var_dump($a); // [/php] // The above example will output: // [result] // array(3) { // [0]=> // string(5) "First" // [2]=> // string(4) "Last" // [1]=> // string(6) "Middle" // } // array(3) { // [0]=> // string(5) "First" // [1]=> // string(6) "Middle" // [2]=> // string(4) "Last" // } // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.ksort.php // ========== KSORT - END // SYNTAX: // bool ksort(array& $array, int $flags = SORT_REGULAR) return $return_ksort; // bool } // ============================== END // PHP_VARIABLE_ARRAY_KSORT // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_LIST // ============================== OFFLINE // ============================== ABOUT // Assign variables as if they were an array. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // list() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE /* function php_variable_array_list($var, $vars) { $return_list = null; // ========== LIST - BEGIN // ===== ABOUT // Assign variables as if they were an array // ===== DESCRIPTION // Like array(), this is not really a function, but a language construct. list() is used to assign a list of variables in one operation. Strings can not be unpacked and list() expressions can not be completely empty. // Note: Before PHP 7.1.0, list() only worked on numerical arrays and assumes the numerical indices start at 0. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // list(mixed $var, mixed ...$vars = ?): array // ===== CODE $return_list = list( $var, // mixed var - A variable. $vars // mixed vars - Further variables. ); // Return Values // Returns the assigned array. // // Changelog // Version - Description // 7.3.0 - Support for reference assignments in array destructuring was added. // 7.1.0 - It is now possible to specify keys in list(). This enables destructuring of arrays with non-integer or non-sequential keys. // // [examples] // Examples // [example] // Example #1 list() examples // [php] // // $info = array('coffee', 'brown', 'caffeine'); // // // Listing all the variables // list($drink, $color, $power) = $info; // echo "$drink is $color and $power makes it special.\n"; // // // Listing some of them // list($drink, , $power) = $info; // echo "$drink has $power.\n"; // // // Or let's skip to only the third one // list( , , $power) = $info; // echo "I need $power!\n"; // // // list() doesn't work with strings // list($bar) = "abcde"; // var_dump($bar); // NULL // [/php] // [/example] // [example] // Example #2 An example use of list() // [php] // $result = $pdo->query("SELECT id, name FROM employees"); // while (list($id, $name) = $result->fetch(PDO::FETCH_NUM)) { // echo "id: $id, name: $name\n"; // } // [/php] // [/example] // [example] // Example #3 Using nested list() // [php] // // list($a, list($b, $c)) = array(1, array(2, 3)); // // var_dump($a, $b, $c); // // [/php] // // [result] // int(1) // int(2) // int(3) // [/result] // [/example] // [example] // Example #4 list() and order of index definitions // The order in which the indices of the array to be consumed by list() are defined is irrelevant. // [php] // $foo = array(2 => 'a', 'foo' => 'b', 0 => 'c'); // $foo[1] = 'd'; // list($x, $y, $z) = $foo; // var_dump($foo, $x, $y, $z); // [/php] // Gives the following output (note the order of the elements compared in which order they were written in the list() syntax): // [result] // array(4) { // [2]=> // string(1) "a" // ["foo"]=> // string(1) "b" // [0]=> // string(1) "c" // [1]=> // string(1) "d" // } // string(1) "c" // string(1) "d" // string(1) "a" // [/result] // [/example] // [example] // Example #5 list() with keys // As of PHP 7.1.0 list() can now also contain explicit keys, which can be given as arbitrary expressions. Mixing of integer and string keys is allowed; however, elements with and without keys cannot be mixed. // [php] // $data = [ // ["id" => 1, "name" => 'Tom'], // ["id" => 2, "name" => 'Fred'], // ]; // foreach ($data as ["id" => $id, "name" => $name]) { // echo "id: $id, name: $name\n"; // } // echo PHP_EOL; // list(1 => $second, 3 => $fourth) = [1, 2, 3, 4]; // echo "$second, $fourth\n"; // [/php] // The above example will output: // [result] // id: 1, name: Tom // id: 2, name: Fred // // 2, 4 // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.list.php // ========== LIST - END // SYNTAX: // array list(mixed $var, mixed $vars) return $return_list; // array } */ // ============================== END // PHP_VARIABLE_ARRAY_LIST // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_NATCASESORT // ============================== PUBLIC // ============================== ABOUT // Sort an array using a case insensitive "natural order" algorithm. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // natcasesort() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_natcasesort(& $array) { $return_natcasesort = false; // ========== NATCASESORT - BEGIN // ===== ABOUT // Sort an array using a case insensitive "natural order" algorithm // ===== DESCRIPTION // natcasesort() is a case insensitive version of natsort(). // This function implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering". // Note: If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined. // Note: Resets array's internal pointer to the first element. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // natcasesort(array &$array): true // ===== CODE $return_natcasesort = natcasesort( $array // array array - The input array. ); // Return Values // Always returns true. // // Changelog // Version - Description // 8.2.0 - The return type is true now; previously, it was bool. // // [examples] // Examples // [example] // Example #1 natcasesort() example // [php] // $array1 = $array2 = array('IMG0.png', 'img12.png', 'img10.png', 'img2.png', 'img1.png', 'IMG3.png'); // // sort($array1); // echo "Standard sorting\n"; // print_r($array1); // // natcasesort($array2); // echo "\nNatural order sorting (case-insensitive)\n"; // print_r($array2); // [/php] // The above example will output: // [result] // Standard sorting // Array // ( // [0] => IMG0.png // [1] => IMG3.png // [2] => img1.png // [3] => img10.png // [4] => img12.png // [5] => img2.png // ) // // Natural order sorting (case-insensitive) // Array // ( // [0] => IMG0.png // [4] => img1.png // [3] => img2.png // [5] => IMG3.png // [2] => img10.png // [1] => img12.png // ) // [/result] // For more information see: Martin Pool's > Natural Order String Comparison page. // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.natcasesort.php // ========== NATCASESORT - END // SYNTAX: // bool natcasesort(array& $array) return $return_natcasesort; // bool } // ============================== END // PHP_VARIABLE_ARRAY_NATCASESORT // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_NATSORT // ============================== PUBLIC // ============================== ABOUT // Sort an array using a "natural order" algorithm. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // natsort() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_natsort(& $array) { $return_natsort = false; // ========== NATSORT - BEGIN // ===== ABOUT // Sort an array using a "natural order" algorithm // ===== DESCRIPTION // This function implements a sort algorithm that orders alphanumeric strings in the way a human being would while maintaining key/value associations. This is described as a "natural ordering". An example of the difference between this algorithm and the regular computer string sorting algorithms (used in sort()) can be seen in the example below. // Note: If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined. // Note: Resets array's internal pointer to the first element. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // natsort(array &$array): true // ===== CODE $return_natsort = natsort( $array // array array - The input array. ); // Return Values // Always returns true. // // Changelog // Version - Description // 8.2.0 - The return type is true now; previously, it was bool. // // [examples] // Examples // [example] // Example #1 natsort() examples demonstrating basic usage // [php] // $array1 = $array2 = array("img12.png", "img10.png", "img2.png", "img1.png"); // // asort($array1); // echo "Standard sorting\n"; // print_r($array1); // // natsort($array2); // echo "\nNatural order sorting\n"; // print_r($array2); // [/php] // The above example will output: // [result] // Standard sorting // Array // ( // [3] => img1.png // [1] => img10.png // [0] => img12.png // [2] => img2.png // ) // // Natural order sorting // Array // ( // [3] => img1.png // [2] => img2.png // [1] => img10.png // [0] => img12.png // ) // [/result] // For more information see: Martin Pool's > Natural Order String Comparison page. // [/example] // [example] // Example #2 natsort() examples demonstrating potential gotchas // [php] // echo "Negative numbers\n"; // $negative = array('-5','3','-2','0','-1000','9','1'); // print_r($negative); // natsort($negative); // print_r($negative); // // echo "Zero padding\n"; // $zeros = array('09', '8', '10', '009', '011', '0'); // print_r($zeros); // natsort($zeros); // print_r($zeros); // [/php] // The above example will output: // [result] // Negative numbers // Array // ( // [0] => -5 // [1] => 3 // [2] => -2 // [3] => 0 // [4] => -1000 // [5] => 9 // [6] => 1 // ) // Array // ( // [2] => -2 // [0] => -5 // [4] => -1000 // [3] => 0 // [6] => 1 // [1] => 3 // [5] => 9 // ) // // Zero padding // Array // ( // [0] => 09 // [1] => 8 // [2] => 10 // [3] => 009 // [4] => 011 // [5] => 0 // ) // Array // ( // [5] => 0 // [1] => 8 // [3] => 009 // [0] => 09 // [2] => 10 // [4] => 011 // ) // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.natsort.php // ========== NATSORT - END // SYNTAX: // bool natsort(array& $array) return $return_natsort; // bool } // ============================== END // PHP_VARIABLE_ARRAY_NATSORT // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_NEXT // ============================== PUBLIC // ============================== ABOUT // Advance the internal pointer of an array. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // next() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_next(& $array) { $return_next = null; // ========== NEXT - BEGIN // ===== ABOUT // Advance the internal pointer of an array // ===== DESCRIPTION // next() behaves like current(), with one difference. It advances the internal array pointer one place forward before returning the element value. That means it returns the next array value and advances the internal array pointer by one. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // next(array|object &$array): mixed // ===== CODE $return_next = next( $array // array|object& array - The array being affected. ); // Return Values // Returns the array value in the next place that's pointed to by the internal array pointer, or false if there are no more elements. // Warning: This function may return Boolean false, but may also return a non-Boolean value which evaluates to false. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function. // // Changelog // Version - Description // 8.1.0 - Calling this function on objects is deprecated. Either convert the object to an array using get_mangled_object_vars() first, or use the methods provided by a class that implements Iterator, such as ArrayIterator, instead. // 7.4.0 - Instances of SPL classes are now treated like empty objects that have no properties instead of calling the Iterator method with the same name as this function. // // [examples] // Examples // [example] // Example #1 Example use of next() and friends // [php] // $transport = array('foot', 'bike', 'car', 'plane'); // $mode = current($transport); // $mode = 'foot'; // $mode = next($transport); // $mode = 'bike'; // $mode = next($transport); // $mode = 'car'; // $mode = prev($transport); // $mode = 'bike'; // $mode = end($transport); // $mode = 'plane'; // [/php] // [/example] // [/examples] // // Notes // Note: The end of an array is indistinguishable from a bool false element. To properly traverse an array which may contain false elements, see the foreach function. To still use next() and properly check if the end of the array has been reached, verify that the key() is null. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-21) // URL: https://www.php.net/manual/en/function.next.php // ========== NEXT - END // SYNTAX: // mixed next(array|object& $array) return $return_next; // mixed } // ============================== END // PHP_VARIABLE_ARRAY_NEXT // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_POS // ============================== PUBLIC // ============================== ABOUT // Return the current element in an array. // // pos - Alias of current(). // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // pos() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_pos($array) { $return_pos = null; // ========== POS - BEGIN // ===== ABOUT // pos - Alias of current() // ===== DESCRIPTION // This function is an alias of: current() // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // ===== CODE $return_pos = pos( $array // array|object $array ); // Return // mixed // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-21) // URL: https://www.php.net/manual/en/function.pos.php // ========== POS - END // ========== CURRENT - BEGIN // ===== ABOUT // Return the current element in an array // ===== DESCRIPTION // Every array has an internal pointer to its "current" element, which is initialized to the first element inserted into the array. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // current(array|object $array): mixed // ===== CODE // $return_current = current( // $array // array|object array - The array. // ); // Return Values // The current() function simply returns the value of the array element that's currently being pointed to by the internal pointer. It does not move the pointer in any way. If the internal pointer points beyond the end of the elements list or the array is empty, current() returns false. // Warning: This function may return Boolean false, but may also return a non-Boolean value which evaluates to false. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function. // // Changelog // Version - Description // 8.1.0 - Calling this function on objects is deprecated. Either convert the object to an array using get_mangled_object_vars() first, or use the methods provided by a class that implements Iterator, such as ArrayIterator, instead. // 7.4.0 - Instances of SPL classes are now treated like empty objects that have no properties instead of calling the Iterator method with the same name as this function. // // [examples] // Examples // [example] // Example #1 Example use of current() and friends // [php] // $transport = array('foot', 'bike', 'car', 'plane'); // $mode = current($transport); // $mode = 'foot'; // $mode = next($transport); // $mode = 'bike'; // $mode = current($transport); // $mode = 'bike'; // $mode = prev($transport); // $mode = 'foot'; // $mode = end($transport); // $mode = 'plane'; // $mode = current($transport); // $mode = 'plane'; // // $arr = array(); // var_dump(current($arr)); // bool(false) // // $arr = array(array()); // var_dump(current($arr)); // array(0) { } // [/php] // [/example] // [/examples] // // Notes // Note: The results of calling current() on an empty array and on an array, whose internal pointer points beyond the end of the elements, are indistinguishable from a bool false element. To properly traverse an array which may contain false elements, see the foreach control structure. To still use current() and properly check if the value is really an element of the array, the key() of the current() element should be checked to be strictly different from null. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-21) // URL: https://www.php.net/manual/en/function.current.php // ========== CURRENT - END // SYNTAX: // mixed pos(array|object $array) return $return_pos; // mixed } // ============================== END // PHP_VARIABLE_ARRAY_POS // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_PREV // ============================== PUBLIC // ============================== ABOUT // Rewind the internal array pointer. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // prev() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_prev(& $array) { $return_prev = null; // ========== PREV - BEGIN // ===== ABOUT // Rewind the internal array pointer // ===== DESCRIPTION // Rewind the internal array pointer. // prev() behaves just like next(), except it rewinds the internal array pointer one place instead of advancing it. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // prev(array|object &$array): mixed // ===== CODE $return_prev = prev( $array // array|object& array - The input array. ); // Return Values // Returns the array value in the previous place that's pointed to by the internal array pointer, or false if there are no more elements. // Warning: This function may return Boolean false, but may also return a non-Boolean value which evaluates to false. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function. // // Changelog // Version - Description // 8.1.0 - Calling this function on objects is deprecated. Either convert the object to an array using get_mangled_object_vars() first, or use the methods provided by a class that implements Iterator, such as ArrayIterator, instead. // 7.4.0 - Instances of SPL classes are now treated like empty objects that have no properties instead of calling the Iterator method with the same name as this function. // // [examples] // Examples // [example] // Example #1 Example use of prev() and friends // [php] // $transport = array('foot', 'bike', 'car', 'plane'); // $mode = current($transport); // $mode = 'foot'; // $mode = next($transport); // $mode = 'bike'; // $mode = next($transport); // $mode = 'car'; // $mode = prev($transport); // $mode = 'bike'; // $mode = end($transport); // $mode = 'plane'; // [/php] // [/example] // [/examples] // // Notes // Note: The beginning of an array is indistinguishable from a bool false element. To make the distinction, check that the key() of the prev() element is not null. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-21) // URL: https://www.php.net/manual/en/function.prev.php // ========== PREV - END // SYNTAX: // mixed prev(array|object& $array) return $return_prev; // mixed } // ============================== END // PHP_VARIABLE_ARRAY_PREV // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_RANGE // ============================== PUBLIC // ============================== ABOUT // Create an array containing a range of elements. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // range() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_range($start, $end, $step = 1) { $return_range = null; // ========== RANGE - BEGIN // ===== ABOUT // Create an array containing a range of elements // ===== DESCRIPTION // Create an array containing a range of elements. // If both start and end are strings, and step is int the produced array will be a sequence of bytes. Otherwise, the produced array will be a sequence of numbers. // The sequence is increasing if start is less than equal to end. Otherwise, the sequence is decreasing. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // range(string|int|float $start, string|int|float $end, int|float $step = 1): array // ===== CODE $return_range = range( $start, // string|int|float start - First value of the sequence. $end, // string|int|float end - Last possible value of the sequence. $step // int|float step - step indicates by how much is the produced sequence progressed between values of the sequence. // step may be negative for decreasing sequences. // If step is a float without a fractional part, it is interpreted as int. ); // Return Values // Returns a sequence of elements as an array with the first element being start going up to end, with each value of the sequence being step values apart. // The last element of the returned array is either end or the previous element of the sequence, depending on the value of step. // If both start and end are strings, and step is int the produced array will be a sequence of bytes, generally latin ASCII characters. // If at least one of start, end, or step is float the produced array will be a sequence of float. // Otherwise, the produced array will be a sequence of int. // // Errors/Exceptions // * If step is 0, a ValueError is thrown. // * If start, end, or step is not is_finite(), a ValueError is thrown. // * If step is negative, but the produced range is increasing (i.e. $start <= $end), a ValueError is thrown. // * If start or end is the empty string '', an E_WARNING is emitted and the empty string will be interpreted as 0. // * If start or end non-numeric string with more than one byte, an E_WARNING is emitted. // * If start or end is a string that is implicitly cast to an int because the other boundary value is a number, an E_WARNING is emitted. // * If step is a float, and start and end are non-numeric string, an E_WARNING is emitted. // // Changelog // Version - Description // 8.3.0 - If both start and end are strings then range() will now always produce an array of bytes. Previously if one of the boundary values was a numeric string, then the other boundary value was implicitly cast to int. // 8.3.0 - An E_WARNING is now emitted if start or end is a string that is implicitly cast to int because the other boundary value is a number. // 8.3.0 - An E_WARNING is now emitted if start or end is a non-numeric string with more than one byte. // 8.3.0 - An E_WARNING is now emitted if start or end is the empty string. // 8.3.0 - If step is a float with no fractional part, it will be interpreted as an int. // 8.3.0 - A ValueError is now thrown if step is negative when producing an increasing range. // 8.3.0 - A ValueError is now thrown if step is not finite. // 8.3.0 - A TypeError is now thrown if start or end is an array, object, or resource. Previously they were implicitly cast to int. // // [examples] // Examples // [example] // Example #1 range() examples // [php] // echo implode(', ', range(0, 12)), PHP_EOL; // // echo implode(', ', range(0, 100, 10)), PHP_EOL; // // echo implode(', ', range('a', 'i')), PHP_EOL; // // echo implode(', ', range('c', 'a')), PHP_EOL; // // echo implode(', ', range('A', 'z')), PHP_EOL; // [/php] // The above example will output: // [result] // 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 // 0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100 // a, b, c, d, e, f, g, h, i // c, b, a // A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z, [, \, ], ^, _, `, a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-21) // URL: https://www.php.net/manual/en/function.range.php // ========== RANGE - END // SYNTAX: // array range(string|int|float $start, string|int|float $end, int|float $step = 1) return $return_range; // array } // ============================== END // PHP_VARIABLE_ARRAY_RANGE // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_RESET // ============================== PUBLIC // ============================== ABOUT // Set the internal pointer of an array to its first element. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // reset() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_reset(& $array) { $return_reset = null; // ========== RESET - BEGIN // ===== ABOUT // Set the internal pointer of an array to its first element // ===== DESCRIPTION // reset() rewinds array's internal pointer to the first element and returns the value of the first array element. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // reset(array|object &$array): mixed // ===== CODE $return_reset = reset( $array // array|object& array - The input array. ); // Return Values // Returns the value of the first array element, or false if the array is empty. // Warning: This function may return Boolean false, but may also return a non-Boolean value which evaluates to false. Please read the section on Booleans for more information. Use the === operator for testing the return value of this function. // // Changelog // Version - Description // 8.1.0 - Calling this function on objects is deprecated. Either convert the object to an array using get_mangled_object_vars() first, or use the methods provided by a class that implements Iterator, such as ArrayIterator, instead. // 7.4.0 - Instances of SPL classes are now treated like empty objects that have no properties instead of calling the Iterator method with the same name as this function. // // [examples] // Examples // [example] // Example #1 reset() example // [php] // // $array = array('step one', 'step two', 'step three', 'step four'); // // // by default, the pointer is on the first element // echo current($array) . "
\n"; // "step one" // // // skip two steps // next($array); // next($array); // echo current($array) . "
\n"; // "step three" // // // reset pointer, start again on step one // reset($array); // echo current($array) . "
\n"; // "step one" // // [/php] // [/example] // [/examples] // // Notes // Note: The return value for an empty array is indistinguishable from the return value in case of an array which has a bool false first element. To properly check the value of the first element of an array which may contain false elements, first check the count() of the array, or check that key() is not null, after calling reset(). // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-21) // URL: https://www.php.net/manual/en/function.reset.php // ========== RESET - END // SYNTAX: // mixed reset(array|object& $array) return $return_reset; // mixed } // ============================== END // PHP_VARIABLE_ARRAY_RESET // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_RSORT // ============================== PUBLIC // ============================== ABOUT // Sort an array in descending order. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // rsort() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== USING CONSTANTS (1) // SORT_REGULAR - rsort() // ============================== CODE function php_variable_array_rsort(& $array, $flags = SORT_REGULAR) { $return_rsort = false; // ========== RSORT - BEGIN // ===== ABOUT // Sort an array in descending order // ===== DESCRIPTION // Sorts array in place by values in descending order. // Note: If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined. // Note: This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys. // Note: Resets array's internal pointer to the first element. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // rsort(array &$array, int $flags = SORT_REGULAR): true // ===== CODE $return_rsort = rsort( $array, // array array - The input array. $flags // int flags - The optional second parameter flags may be used to modify the sorting behavior using these values: // // Sorting type flags: // * SORT_REGULAR - compare items normally; the details are described in the comparison operators section // * SORT_NUMERIC - compare items numerically // * SORT_STRING - compare items as strings // * SORT_LOCALE_STRING - compare items as strings, based on the current locale. It uses the locale, which can be changed using setlocale() // * SORT_NATURAL - compare items as strings using "natural ordering" like natsort() // * SORT_FLAG_CASE - can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively ); // Return Values // Always returns true. // // Changelog // Version - Description // 8.2.0 - The return type is true now; previously, it was bool. // // [examples] // Examples // [example] // Example #1 rsort() example // [php] // $fruits = array("lemon", "orange", "banana", "apple"); // rsort($fruits); // foreach ($fruits as $key => $val) { // echo "$key = $val\n"; // } // [/php] // The above example will output: // [result] // 0 = orange // 1 = lemon // 2 = banana // 3 = apple // [/result] // The fruits have been sorted in reverse alphabetical order. // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.rsort.php // ========== RSORT - END // SYNTAX: // bool rsort(array& $array, int $flags = SORT_REGULAR) return $return_rsort; // bool } // ============================== END // PHP_VARIABLE_ARRAY_RSORT // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_SHUFFLE // ============================== PUBLIC // ============================== ABOUT // Shuffle an array. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // shuffle() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_shuffle(& $array) { $return_shuffle = false; // ========== SHUFFLE - BEGIN // ===== ABOUT // Shuffle an array // ===== DESCRIPTION // This function shuffles (randomizes the order of the elements in) an array. // Caution: This function does not generate cryptographically secure values, and must not be used for cryptographic purposes, or purposes that require returned values to be unguessable. // If cryptographically secure randomness is required, the Random\Randomizer may be used with the Random\Engine\Secure engine. For simple use cases, the random_int() and random_bytes() functions provide a convenient and secure API that is backed by the operating system’s CSPRNG. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // shuffle(array &$array): true // ===== CODE $return_shuffle = shuffle( $array // array - The array. ); // Return Values // Always returns true. // // Changelog // Version - Description // 7.1.0 - The internal randomization algorithm has been changed to use the > Mersenne Twister Random Number Generator instead of the libc rand function. // // [examples] // Examples // [example] // Example #1 shuffle() example // [php] // $numbers = range(1, 20); // shuffle($numbers); // foreach ($numbers as $number) { // echo "$number "; // } // [/php] // [/example] // [/examples] // // Notes // Note: This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys. // Note: Resets array's internal pointer to the first element. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.shuffle.php // ========== SHUFFLE - END // SYNTAX: // bool shuffle(array& $array) return $return_shuffle; // bool } // ============================== END // PHP_VARIABLE_ARRAY_SHUFFLE // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_SIZEOF // ============================== PUBLIC // ============================== ABOUT // Counts all elements in an array or in a Countable object. // // sizeof - Alias of count(). // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // sizeof() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== USING CONSTANTS (1) // COUNT_NORMAL - sizeof() // ============================== CODE function php_variable_array_sizeof($value, $mode = COUNT_NORMAL) { $return_sizeof = 0; // ========== SIZEOF - BEGIN // ===== ABOUT // sizeof - Alias of count() // ===== DESCRIPTION // This function is an alias of: count(). // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // ===== CODE $return_sizeof = sizeof( $value, // Countable|array $value $mode // int $mode ); // Return // int // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-21) // URL: https://www.php.net/manual/en/function.sizeof.php // ========== SIZEOF - END // ========== COUNT - BEGIN // ===== ABOUT // Counts all elements in an array or in a Countable object // ===== DESCRIPTION // Counts all elements in an array when used with an array. When used with an object that implements the Countable interface, it returns the return value of the method Countable::count(). // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // count(Countable|array $value, int $mode = COUNT_NORMAL): int // ===== CODE // $return_count = count( // $value, // Countable|array value - An array or Countable object. // $mode // int mode - If the optional mode parameter is set to COUNT_RECURSIVE (or 1), count() will recursively count the array. This is particularly useful for counting all the elements of a multidimensional array. // Caution: count() can detect recursion to avoid an infinite loop, but will emit an E_WARNING every time it does (in case the array contains itself more than once) and return a count higher than may be expected. // ); // Return Values // Returns the number of elements in value. Prior to PHP 8.0.0, if the parameter was neither an array nor an object that implements the Countable interface, 1 would be returned, unless value was null, in which case 0 would be returned. // // Changelog // Version - Description // 8.0.0 - count() will now throw TypeError on invalid countable types passed to the value parameter. // 7.2.0 - count() will now yield a warning on invalid countable types passed to the value parameter. // // [examples] // Examples // [example] // Example #1 count() example // [php] // $a[0] = 1; // $a[1] = 3; // $a[2] = 5; // var_dump(count($a)); // // $b[0] = 7; // $b[5] = 9; // $b[10] = 11; // var_dump(count($b)); // [/php] // The above example will output: // [result] // int(3) // int(3) // [/result] // [/example] // [example] // Example #2 count() non Countable|array example (bad example - don't do this) // [php] // $b[0] = 7; // $b[5] = 9; // $b[10] = 11; // var_dump(count($b)); // // var_dump(count(null)); // // var_dump(count(false)); // [/php] // The above example will output: // [result] // int(3) // int(0) // int(1) // [/result] // Output of the above example in PHP 7.2: // [result] // int(3) // // Warning: count(): Parameter must be an array or an object that implements Countable in … on line 12 // int(0) // // Warning: count(): Parameter must be an array or an object that implements Countable in … on line 14 // int(1) // [/result] // Output of the above example in PHP 8: // [result] // int(3) // // Fatal error: Uncaught TypeError: count(): Argument #1 ($var) must be of type Countable .. on line 12 // [/result] // [/example] // [example] // Example #3 Recursive count() example // [php] // $food = array('fruits' => array('orange', 'banana', 'apple'), // 'veggie' => array('carrot', 'collard', 'pea')); // // // recursive count // var_dump(count($food, COUNT_RECURSIVE)); // // // normal count // var_dump(count($food)); // // [/php] // The above example will output: // [result] // int(8) // int(2) // [/result] // [/example] // [example] // Example #4 Countable object // [php] // class CountOfMethods implements Countable // { // private function someMethod() // { // } // // public function count(): int // { // return count(get_class_methods($this)); // } // } // // $obj = new CountOfMethods(); // var_dump(count($obj)); // [/php] // The above example will output: // [result] // int(2) // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-21) // URL: https://www.php.net/manual/en/function.count.php // ========== COUNT - END // SYNTAX: // int sizeof(Countable|array $value, int $mode = COUNT_NORMAL) return $return_sizeof; // int } // ============================== END // PHP_VARIABLE_ARRAY_SIZEOF // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_SORT // ============================== PUBLIC // ============================== ABOUT // Sort an array in ascending order. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // sort() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== USING CONSTANTS (1) // SORT_REGULAR - sort() // ============================== CODE function php_variable_array_sort(& $array, $flags = SORT_REGULAR) { $return_sort = false; // ========== SORT - BEGIN // ===== ABOUT // Sort an array in ascending order // ===== DESCRIPTION // Sorts array in place by values in ascending order. // Note: If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined. // Note: This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys. // Note: Resets array's internal pointer to the first element. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // sort(array &$array, int $flags = SORT_REGULAR): true // ===== CODE $return_sort = sort( $array, // array array - The input array. $flags // int flags - The optional second parameter flags may be used to modify the sorting behavior using these values: // // Sorting type flags: // * SORT_REGULAR - compare items normally; the details are described in the comparison operators section // * SORT_NUMERIC - compare items numerically // * SORT_STRING - compare items as strings // * SORT_LOCALE_STRING - compare items as strings, based on the current locale. It uses the locale, which can be changed using setlocale() // * SORT_NATURAL - compare items as strings using "natural ordering" like natsort() // * SORT_FLAG_CASE - can be combined (bitwise OR) with SORT_STRING or SORT_NATURAL to sort strings case-insensitively ); // Return Values // Always returns true. // // Changelog // Version - Description // 8.2.0 - The return type is true now; previously, it was bool. // // [examples] // Examples // [example] // Example #1 sort() example // [php] // // $fruits = array("lemon", "orange", "banana", "apple"); // sort($fruits); // foreach ($fruits as $key => $val) { // echo "fruits[" . $key . "] = " . $val . "\n"; // } // // [/php] // The above example will output: // [result] // fruits[0] = apple // fruits[1] = banana // fruits[2] = lemon // fruits[3] = orange // [/result] // The fruits have been sorted in alphabetical order. // [/example] // [example] // Example #2 sort() example using case-insensitive natural ordering // [php] // // $fruits = array( // "Orange1", "orange2", "Orange3", "orange20" // ); // sort($fruits, SORT_NATURAL | SORT_FLAG_CASE); // foreach ($fruits as $key => $val) { // echo "fruits[" . $key . "] = " . $val . "\n"; // } // // [/php] // The above example will output: // [result] // fruits[0] = Orange1 // fruits[1] = orange2 // fruits[2] = Orange3 // fruits[3] = orange20 // [/result] // The fruits have been sorted like natcasesort(). // [/example] // [/examples] // // Notes // Note: Like most PHP sorting functions, sort() uses an implementation of > Quicksort. The pivot is chosen in the middle of the partition resulting in an optimal time for already sorted arrays. This is however an implementation detail you shouldn't rely on. // Warning: Be careful when sorting arrays with mixed types values because sort() can produce unexpected results, if flags is SORT_REGULAR. // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.sort.php // ========== SORT - END // SYNTAX: // bool sort(array& $array, int $flags = SORT_REGULAR) return $return_sort; // bool } // ============================== END // PHP_VARIABLE_ARRAY_SORT // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_UASORT // ============================== PUBLIC // ============================== ABOUT // Sort an array with a user-defined comparison function and maintain index association. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // uasort() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_uasort(& $array, $callback) { $return_uasort = false; // ========== UASORT - BEGIN // ===== ABOUT // Sort an array with a user-defined comparison function and maintain index association // ===== DESCRIPTION // Sorts array in place such that its keys maintain their correlation with the values they are associated with, using a user-defined comparison function. // This is used mainly when sorting associative arrays where the actual element order is significant. // Note: If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined. // Note: Resets array's internal pointer to the first element. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // uasort(array &$array, callable $callback): true // ===== CODE $return_uasort = uasort( $array, // array array - The input array. $callback // callable callback - The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. // callback(mixed $a, mixed $b): int // Caution: Returning non-integer values from the comparison function, such as float, will result in an internal cast to int of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal. ); // Return Values // Always returns true. // // Changelog // Version - Description // 8.2.0 - The return type is true now; previously, it was bool. // 8.0.0 - If callback expects a parameter to be passed by reference, this function will now emit an E_WARNING. // // [examples] // Examples // [example] // Example #1 Basic uasort() example // [php] // // Comparison function // function cmp($a, $b) { // if ($a == $b) { // return 0; // } // return ($a < $b) ? -1 : 1; // } // // // Array to be sorted // $array = array('a' => 4, 'b' => 8, 'c' => -1, 'd' => -9, 'e' => 2, 'f' => 5, 'g' => 3, 'h' => -4); // print_r($array); // // // Sort and print the resulting array // uasort($array, 'cmp'); // print_r($array); // [/php] // The above example will output: // [result] // Array // ( // [a] => 4 // [b] => 8 // [c] => -1 // [d] => -9 // [e] => 2 // [f] => 5 // [g] => 3 // [h] => -4 // ) // Array // ( // [d] => -9 // [h] => -4 // [c] => -1 // [e] => 2 // [g] => 3 // [a] => 4 // [f] => 5 // [b] => 8 // ) // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.uasort.php // ========== UASORT - END // SYNTAX: // bool uasort(array& $array, callable $callback) return $return_uasort; // bool } // ============================== END // PHP_VARIABLE_ARRAY_UASORT // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_UKSORT // ============================== PUBLIC // ============================== ABOUT // Sort an array by keys using a user-defined comparison function. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // uksort() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_uksort(& $array, $callback) { $return_uksort = false; // ========== UKSORT - BEGIN // ===== ABOUT // Sort an array by keys using a user-defined comparison function // ===== DESCRIPTION // Sorts array in place by keys using a user-supplied comparison function to determine the order. // Note: If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined. // Note: Resets array's internal pointer to the first element. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // uksort(array &$array, callable $callback): true // ===== CODE $return_uksort = uksort( $array, // array array - The input array. $callback // callable callback - The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. // callback(mixed $a, mixed $b): int // Caution: Returning non-integer values from the comparison function, such as float, will result in an internal cast to int of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal. ); // Return Values // Always returns true. // // Changelog // Version - Description // 8.2.0 - The return type is true now; previously, it was bool. // 8.0.0 - If callback expects a parameter to be passed by reference, this function will now emit an E_WARNING. // // [examples] // Examples // [example] // Example #1 uksort() example // [php] // function cmp($a, $b) // { // $a = preg_replace('@^(a|an|the) @', '', $a); // $b = preg_replace('@^(a|an|the) @', '', $b); // return strcasecmp($a, $b); // } // // $a = array("John" => 1, "the Earth" => 2, "an apple" => 3, "a banana" => 4); // // uksort($a, "cmp"); // // foreach ($a as $key => $value) { // echo "$key: $value\n"; // } // [/php] // The above example will output: // [result] // an apple: 3 // a banana: 4 // the Earth: 2 // John: 1 // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.uksort.php // ========== UKSORT - END // SYNTAX: // bool uksort(array& $array, callable $callback) return $return_uksort; // bool } // ============================== END // PHP_VARIABLE_ARRAY_UKSORT // ============================== // ============================== BEGIN // PHP_VARIABLE_ARRAY_USORT // ============================== PUBLIC // ============================== ABOUT // Sort an array by values using a user-defined comparison function. // ============================== SUPPORT // PHP_4 - PHP_8 // ============================== USING FUNCTIONS (1) // usort() - PHP_4, PHP_5, PHP_7, PHP_8 // ============================== CODE function php_variable_array_usort(& $array, $callback) { $return_usort = false; // ========== USORT - BEGIN // ===== ABOUT // Sort an array by values using a user-defined comparison function // ===== DESCRIPTION // Sorts array in place by values using a user-supplied comparison function to determine the order. // Note: If two members compare as equal, they retain their original order. Prior to PHP 8.0.0, their relative order in the sorted array was undefined. // Note: This function assigns new keys to the elements in array. It will remove any existing keys that may have been assigned, rather than just reordering the keys. // ===== SUPPORTED // PHP_4, PHP_5, PHP_7, PHP_8 // ===== SYNTAX // usort(array &$array, callable $callback): true // ===== CODE $return_usort = usort( $array, // array array - The input array. $callback // callable callback - The comparison function must return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. // callback(mixed $a, mixed $b): int // Caution: Returning non-integer values from the comparison function, such as float, will result in an internal cast to int of the callback's return value. So values such as 0.99 and 0.1 will both be cast to an integer value of 0, which will compare such values as equal. ); // Return Values // Always returns true. // // Changelog // Version - Description // 8.2.0 - The return type is true now; previously, it was bool. // 8.0.0 - If callback expects a parameter to be passed by reference, this function will now emit an E_WARNING. // // [examples] // Examples // [example] // Example #1 usort() example // [php] // function cmp($a, $b) // { // if ($a == $b) { // return 0; // } // return ($a < $b) ? -1 : 1; // } // // $a = array(3, 2, 5, 6, 1); // // usort($a, "cmp"); // // foreach ($a as $key => $value) { // echo "$key: $value\n"; // } // [/php] // The above example will output: // [result] // 0: 1 // 1: 2 // 2: 3 // 3: 5 // 4: 6 // [/result] // The spaceship operator may be used to simplify the internal comparison even further. // [php] // function cmp($a, $b) // { // return $a <=> $b; // } // // $a = array(3, 2, 5, 6, 1); // // usort($a, "cmp"); // // foreach ($a as $key => $value) { // echo "$key: $value\n"; // } // [/php] // Note: Obviously in this trivial case the sort() function would be more appropriate. // [/example] // [example] // Example #2 usort() example using multi-dimensional array // [php] // function cmp($a, $b) // { // return strcmp($a["fruit"], $b["fruit"]); // } // // $fruits[0]["fruit"] = "lemons"; // $fruits[1]["fruit"] = "apples"; // $fruits[2]["fruit"] = "grapes"; // // usort($fruits, "cmp"); // // foreach ($fruits as $key => $value) { // echo "\$fruits[$key]: " . $value["fruit"] . "\n"; // } // [/php] // When sorting a multi-dimensional array, $a and $b contain references to the first index of the array. // The above example will output: // [result] // $fruits[0]: apples // $fruits[1]: grapes // $fruits[2]: lemons // [/result] // [/example] // [example] // Example #3 usort() example using a member function of an object // [php] // class TestObj { // private string $name; // // function __construct($name) // { // $this->name = $name; // } // // /* This is the static comparing function: */ // static function cmp_obj($a, $b) // { // return strtolower($a->name) <=> strtolower($b->name); // } // } // // $a[] = new TestObj("c"); // $a[] = new TestObj("b"); // $a[] = new TestObj("d"); // // usort($a, [TestObj::class, "cmp_obj"]); // // foreach ($a as $item) { // echo $item->name . "\n"; // } // [/php] // The above example will output: // [result] // b // c // d // [/result] // [/example] // [example] // Example #4 usort() example using a closure to sort a multi-dimensional array // [php] // $array[0] = array('key_a' => 'z', 'key_b' => 'c'); // $array[1] = array('key_a' => 'x', 'key_b' => 'b'); // $array[2] = array('key_a' => 'y', 'key_b' => 'a'); // // function build_sorter($key) { // return function ($a, $b) use ($key) { // return strnatcmp($a[$key], $b[$key]); // }; // } // // usort($array, build_sorter('key_b')); // // foreach ($array as $item) { // echo $item['key_a'] . ', ' . $item['key_b'] . "\n"; // } // [/php] // The above example will output: // [result] // y, a // x, b // z, c // [/result] // [/example] // [example] // Example #5 usort() example using the spaceship operator // The spaceship operator allows for straightforward comparison of compound values across multiple axes. The following example will sort $people by last name, then by first name if the last name matches. // [php] // $people[0] = ['first' => 'Adam', 'last' => 'West']; // $people[1] = ['first' => 'Alec', 'last' => 'Baldwin']; // $people[2] = ['first' => 'Adam', 'last' => 'Baldwin']; // // function sorter(array $a, array $b) { // return [$a['last'], $a['first']] <=> [$b['last'], $b['first']]; // } // // usort($people, 'sorter'); // // foreach ($people as $person) { // print $person['last'] . ', ' . $person['first'] . PHP_EOL; // } // [/php] // The above example will output: // [result] // Baldwin, Adam // Baldwin, Alec // West, Adam // [/result] // [/example] // [/examples] // ===== LITERATURE_SOURCES // * PHP_NET (2024-01-20) // URL: https://www.php.net/manual/en/function.usort.php // ========== USORT - END // SYNTAX: // bool usort(array& $array, callable $callback) return $return_usort; // bool } // ============================== END // PHP_VARIABLE_ARRAY_USORT // ============================== // ============================== END // PHP_VARIABLE_ARRAY // ============================== ?>