Using natsort in PHP

natsort –  Sort an array using a “natural order” algorithm

Description

void natsort ( array array)

This function implements a sort algorithm that orders alphanumeric strings in the way a human being would. 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 below:

Example 1. natsort() example

<?php
$array1
= $array2 = array(“img12.png”, “img10.png”, “img2.png”, “img1.png”);

sort($array1);
echo
“Standard sorting\n”;
print_r($array1);

natsort($array2);
echo
“\nNatural order sorting\n”;
print_r($array2);
?>

The code above will generate the following output:

Standard sorting
Array
(
    [0] => img1.png
    [1] => img10.png
    [2] => img12.png
    [3] => img2.png
)

Natural order sorting
Array
(
    [3] => img1.png
    [2] => img2.png
    [1] => img10.png
    [0] => img12.png
)

Note: If you’re wanting to maintain index/value associations, consider using uasort($arr, ’strnatcmp’).

Using natcasesort in PHP

natcasesort –  Sort an array using a case insensitive “natural order” algorithm

Description

void natcasesort ( array array)

This function implements a sort algorithm that orders alphanumeric strings in the way a human being would. This is described as a “natural ordering”.

natcasesort() is a case insensitive version of natsort(). See natsort() for an example of the difference between this algorithm and the regular computer string sorting algorithms.

Using list function in PHP

list –  Assign variables as if they were an array

Description

void list ( mixed …)

Like array(), this is not really a function, but a language construct. list() is used to assign a list of variables in one operation.

Note: list() only works on numerical arrays and assumes the numerical indices start at 0.

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;

?>

Example 2. An example use of list()

<table>
<tr>
<th>Employee name</th>
<th>Salary</th>
</tr>

<?php

$result = mysql_query(“SELECT id, name, salary FROM employees”, $conn);
while (list(
$id, $name, $salary) = mysql_fetch_row($result)) {
echo
” <tr>\n” .
“  <td><a href=\”info.php?id=$id\”>$name</a></td>\n.
“  <td>$salary</td>\n.
” </tr>\n”;
}

?>

</table>

Warning
list() assigns the values starting with the right-most parameter. If you are using plain variables, you don’t have to worry about this. But if you are using arrays with indices you usually expect the order of the indices in the array the same you wrote in the list() from left to right; which it isn’t. It’s assigned in the reverse order.

Example 3. Using list() with array indices

<?php

$info = array(‘coffee’, ‘brown’, ‘caffeine’);

list($a[0], $a[1], $a[2]) = $info;

var_dump($a);

?>

Gives the following output (note the order of the elements compared in which order they were written in the list() syntax):

array(3) {
  [2]=>
  string(8) "caffeine"
  [1]=>
  string(5) "brown"
  [0]=>
  string(6) "coffee"
}

Using ksort in PHP

ksort – Sort an array by key

Description

bool ksort ( array array [, int sort_flags])

Sorts an array by key, maintaining key to data correlations. This is useful mainly for associative arrays.

Returns TRUE on success or FALSE on failure.

Example 1. ksort() example

<?php
$fruits
= array(“d”=>“lemon”, “a”=>“orange”, “b”=>“banana”, “c”=>“apple”);
ksort($fruits);
reset($fruits);
while (list(
$key, $val) = each($fruits)) {
echo
“$key = $val\n;
}
?>

This example would display:

a = orange
b = banana
c = apple
d = lemon

You may modify the behavior of the sort using the optional parameter sort_flags

Using krsort in PHP

krsort – Sort an array by key in reverse order

Description

bool krsort ( array array [, int sort_flags])

Sorts an array by key in reverse order, maintaining key to data correlations. This is useful mainly for associative arrays.

Returns TRUE on success or FALSE on failure.

Example 1. krsort() example

<?php
$fruits
= array(“d”=>“lemon”, “a”=>“orange”, “b”=>“banana”, “c”=>“apple”);
krsort($fruits);
reset($fruits);
while (list(
$key, $val) = each($fruits)) {
echo
“$key = $val\n;
}
?>

This example would display:

d = lemon
c = apple
b = banana
a = orange

You may modify the behavior of the sort using the optional parameter sort_flags

Using key in PHP

key – Fetch a key from an associative array

Description

mixed key ( array array)

key() returns the index element of the current array position.

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).‘<br />’;
}
next($array);
}
?>

Using in_array in PHP

in_array – Checks if a value exists in an array

Description

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

Searches haystack for needle and returns TRUE if it is found in the array, FALSE otherwise.

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: If needle is a string, the comparison is done in a case-sensitive manner.

Note: In PHP versions before 4.2.0 needle was not allowed to be an array.

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”;
}
?>

The second condition fails because in_array() is case-sensitive, so the program above will display:

Got Irix

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”;
}
?>

This will display:

1.13 found with strict check

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”;
}
?>

Outputs:

'ph' was found
  'o' was found

Using extract in PHP

extract –  Import variables into the current symbol table from an array

Description

int extract ( array var_array [, int extract_type [, string prefix]])

This function is used to import variables from an array into the current symbol table. It takes an associative array var_array and 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 extract_type and prefix parameters.

Note: Beginning with version 4.0.5, this function returns the number of variables extracted.

Note: EXTR_IF_EXISTS and EXTR_PREFIX_IF_EXISTS was introduced in version 4.2.0.

Note: EXTR_REFS was introduced in version 4.3.0.

extract() checks each key to see whether it has a valid variable name. It also checks for collisions with existing variables in the symbol table. The way invalid/numeric keys and collisions are treated is determined by the extract_type. 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. Beginning with PHP 4.0.5, this includes numeric variables as well.

EXTR_PREFIX_INVALID
Only prefix invalid/numeric variable names with prefix. This flag was added in PHP 4.0.5.

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. This flag was added in PHP 4.2.0.

EXTR_PREFIX_IF_EXISTS
Only create prefixed variable names if the non-prefixed version of the same variable exists in the current symbol table. This flag was added in PHP 4.2.0.

EXTR_REFS
Extracts variables as references. This effectively means that the values of the imported variables are still referencing the values of the var_array parameter. You can use this flag on its own or combine it with any other flag by OR’ing the extract_type. This flag was added in PHP 4.3.0.

If extract_type is not specified, it is assumed to be EXTR_OVERWRITE.

Note that prefix is only required if extract_type 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.

extract() returns the number of variables successfully imported into the symbol table.

A possible use for extract() is to import into the symbol table variables contained in an associative array returned by wddx_deserialize().

Example 1. extract() example

<?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;

?>

The above example will produce:

blue, large, sphere, medium

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.

You must use an associative array, a numerically indexed array will not produce results unless you use EXTR_PREFIX_ALL or EXTR_PREFIX_INVALID.

Using end in PHP

end –  Set the internal pointer of an array to its last element

Description

mixed end ( array array)

end() advances array’s internal pointer to the last element, and returns the value from the last element.

Example 1. A simple end() example

<?php

$fruits = array(‘apple’, ‘banana’, ‘cranberry’);

echo end($fruits); // cranberry

?>

Using each in PHP

each –  Return the current key and value pair from an array and advance the array cursor

Description

array each ( array array)

Returns the current key and value pair from the array array and advances the array cursor. 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.

Example 1. each() examples

<?php
$foo
= array(“bob”, “fred”, “jussi”, “jouni”, “egon”, “marliese”);
$bar = each($foo);
print_r($bar);
?>

$bar now contains the following key/value pairs:

Array
(
    [1] => bob
    [value] => bob
    [0] => 0
    [key] => 0
)

<?php
$foo
= array(“Robert” => “Bob”, “Seppo” => “Sepi”);
$bar = each($foo);
print_r($bar);
?>

$bar now contains the following key/value pairs:

Array
(
    [1] => Bob
    [value] => Bob
    [0] => Robert
    [key] => Robert
)

each() is typically used in conjunction with list() to traverse an array, here’s an 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;
}
?>

Outputs:

a => apple
b => banana
c => cranberry

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.

Caution
Because assigning an array to another variable resets the original arrays pointer, our example above would cause an endless loop had we assigned $fruit to another variable inside the loop.