• Blogs (9)
    • 📱 236 - 992 - 3846

      📧 jxjwilliam@gmail.com

    • Version: ‍🚀 1.1.0
  • php sort, array_search

    Blogs20102010-11-10


    I sum up 3 types of general php functions: sort, array search, and string/array split. Clearly understanding them would be very useful for coding.

    Sorting Arrays

    • 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, low to high (ascending), high to low (descending), numerical, 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 the order is undefined (the sorting is not stable).

    Sorting function attributes | Function name | Sorts by | Maintains key association | Order of sort | Related functions | | --- | --- | --- | --- | --- | | array_multisort() | value | associative yes, numeric no | first array or sort options | array_walk() | | asort() | value | yes | low to high | arsort() | | arsort() | value | yes | high to low | asort() | | krsort() | key | yes | high to low | ksort() | | ksort() | key | yes | low to high | asort() | | natcasesort() | value | yes | natural, case insensitive | natsort() | | natsort() | value | yes | natural | natcasesort() | | rsort() | value | no | high to low | sort() | | shuffle() | value | no | random | array_rand() | | sort() | value | no | low to high | rsort() | | uasort() | value | yes | user defined | uksort() | | uksort() | key | yes | user defined | uasort() | | usort() | value | no | user defined | uasort() |

    3 main sort functions:

    • sort
      Sorts an array in alphabetical order based on the value of each element. The index keys will also be renumbered 0 to length – 1. This is used primarily on arrays where the indexes/keys do not matter.
    • asort()
      Like the sort() function, this sorts the array in alphabetical order based on the value of each element, however, unlike the sort() function, all indexes are maintained, thus it will not renumber them, but rather keep them. This is particularly useful with associate arrays.
    • ksort()
      Sorts an array in alphabetical order by index/key. This is typically used for associate arrays where you want the keys/indexes to be in alphabetical order.

    Array search functions comparation

    Array function Description Return values Examples
    array_search

    Searches the array for a given value and returns the corresponding key if successful

    mixed array_search ( mixed $needle , array $haystack [, bool $strict ] )

    |

    Returns the key for needle if it is found in the array, FALSE otherwise.

    | $array = array(0 => ‘blue’, 1 => ‘red’, 2 => ‘green’, 3 => ‘red’);

    $key = array_search(‘green’, $array); // $key = 2;
    $key = array_search(‘red’, $array); // $key = 1; | |

    array_keys

    |

    array array_keys ( array $input [, mixed $search_value [, bool $strict = false ]] )

    array_keys() returns the keys, numeric and string, from the input array.

    If the optional search\value_ is specified, then only the keys for that value are returned. Otherwise, all the keys from the input are returned.

    | Return all the keys or a subset of the keys of an array |

    $array = array(0 => 100, “color” => “red”);
    print_r(array_keys($array));
    - Array(
    [0] => 0
    [1] => color
    )

    $array = array(“blue”, “red”, “green”, “blue”, “blue”);
    print_r(array_keys($array, “blue”));
    - Array (
    [0] => 0
    [1] => 3
    [2] => 4
    )

    $array = array(“color” => array(“blue”, “red”, “green”),
    “size” => array(“small”, “medium”, “large”));
    print_r(array_keys($array));
    - Array(
    [0] => color
    [1] => size
    )

    | | array_values |

    array array_values ( array $input )

    array_values() returns all the values from the input array and indexes numerically the array.

    | Returns an indexed array of values. |

    $array = array(“size” => “XL”, “color” => “gold”);
    print_r(array_values($array));
    -Array ([0] => XL [1] => gold )

    | | in_array |

    bool in_array ( mixed $needle , array $haystack [, bool $strict ] )

    Searches haystack for needle.

    | Returns TRUE if needle is found in the array, FALSE otherwise. | $os = array(“Mac”, “NT”, “Irix”, “Linux”);
    if (in_array(“Irix”, $os)) {
    echo “Got Irix”;
    }
    if (in_array(“mac”, $os)) {
    echo “Got mac”;
    }
    -Got Irix | | array_key_exists |

    bool array_key_exists ( mixed $key , array $search )

    | Returns TRUE on success or FALSE on failure. | $search_array = array(‘first’ => 1, ‘second’ => 4);
    if (array_key_exists(‘first’, $search_array)) {
    echo “The ‘first’ element is in the array”;
    } |

    String Functions

    • split() function has been DEPRECATED as of PHP 5.3.0.
    • preg_split(), which uses a Perl-compatible regular expression syntax, is often a faster alternative to split(). If you don’t require the power of regular expressions, it is faster to use explode(), which doesn’t incur the overhead of the regular expression engine.
    String Function Description Return values Examples
    explode

    array explode ( string $delimiter , string $string [, int $limit ] )

    |

    Returns an array of strings created by splitting the string parameter on boundaries formed by the delimiter.

    | $pizza = “piece1 piece2 piece3 piece4 piece5 piece6”;
    $pieces = explode(” ”, $pizza);
    echo $pieces[0]; // piece1
    echo $pieces[1]; // piece2

    // Example 2
    $data = “foo:*:1023:1000::/home/foo:/bin/sh”;
    list($user, $pass, $uid, $gid, $gecos, $home, $shell) = explode(”:”, $data);
    echo $user; // foo
    echo $pass; // * | | split |

    array split ( string $pattern , string $string [, int $limit ] )

    Splits a string into array by regular expression.

    |

    Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the case-sensitive regular expression pattern.

    | // Delimiters may be slash, dot, or hyphen
    $date = “04/30/1973”;
    list($month, $day, $year) = split(’[/.-]’, $date);
    echo “Month: $month; Day: $day; Year: $year
    n”; | | implode |

    string implode ( string $glue , array $pieces )

    string implode ( array $pieces )

    Join array elements with a glue string.

    | Returns a string containing a string representation of all the array elements in the same order, with the glue string between each element. | $array = array(‘lastname’, ‘email’, ‘phone’);
    $comma_separated = implode(”,”, $array);

    echo $comma_separated; // lastname,email,phone

    // Empty string when using an empty array:
    var_dump(implode(‘hello’, array())); // string(0) "" | | join |

    join — Alias of implode()

    |   |   | | preg_split |

    array preg_split ( string $pattern , string $subject [, int $limit = -1 [, int $flags = 0 ]] )

    Split the given string by a regular expression.

    | Returns an array containing substrings of subject split along boundaries matched by pattern. | // split the phrase by any number of commas or space characters,
    // which include ” ”, r, t, n and f
    $keywords = preg_split(“/[s,]+/”, “hypertext language, programming”); | | preg_replace |

    mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] ).

    |

    returns an array if the subject parameter is an array, or a string otherwise.

    | $string = ‘April 15, 2003’;
    $pattern = ’/(w+) (d+), (d+)/i’;
    $replacement = ’${1}1,$3’;
    echo preg_replace($pattern, $replacement, $string);
    April1,2003 | | preg_match |

    int preg_match ( string $pattern , string $subject [, array &$matches [, int $flags [, int $offset ]]] )

    | returns the number of times pattern matches. That will be either 0 times (no match) or 1 time because preg_match() will stop searching after the first match. preg_match_all() on the contrary will continue until it reaches the end of subject. preg_match() returns FALSE if an error occurred. | // get host name from URL
    preg_match(’@^(?:http://)?([^/]+)@i’,
    http://www.php.net/index.html”, $matches);
    $host = $matches[1];

    // get last two segments of host name
    preg_match(‘/[^.]+.[^.]+$/’, $host, $matches);
    echo “domain name is: {$matches[0]}n”;
    domain name is: php.net |