|
Home >> FAQs/Tutorials >> PHP Script Tutorials and Tips >> Index
PHP Script Tips - PHP Built-in Functions for Arrays
By: FYICenter.com
Part:
1
2
3
4
5
6
7
(Continued from previous part...)
How To Get All the Values Out of an Array?
Function array_values() returns a new array that contains all the keys of a given array.
Here is a PHP script on how to use array_values():
<?php
$mixed = array();
$mixed["Zero"] = "PHP";
$mixed[1] = "Perl";
$mixed["Two"] = "Java";
$mixed["3"] = "C+";
$mixed[""] = "Basic";
$mixed[] = "Pascal";
$mixed[] = "FORTRAN";
$values = array_values($mixed);
print("Values of the input array:\n");
print_r($values);
?>
This script will print:
Values of the input array:
Array
(
[0] => PHP
[1] => Perl
[2] => Java
[3] => C+
[4] => Basic
[5] => Pascal
[6] => FORTRAN
)
How To Sort an Array by Keys?
Sorting an array by keys can be done by using the ksort() function.
It will re-order all pairs of keys and values based on the alphanumeric order of the keys.
Here is a PHP script on how to use ksort():
<?php
$mixed = array();
$mixed["Zero"] = "PHP";
$mixed[1] = "Perl";
$mixed["Two"] = "Java";
$mixed["3"] = "C+";
$mixed[""] = "Basic";
$mixed[] = "Pascal";
$mixed[] = "FORTRAN";
ksort($mixed);
print("Sorted by keys:\n");
print_r($mixed);
?>
This script will print:
Sorted by keys:
Array
(
[] => Basic
[Two] => Java
[Zero] => PHP
[1] => Perl
[3] => C+
[4] => Pascal
[5] => FORTRAN
)
How To Sort an Array by Values?
Sorting an array by values is doable by using the sort() function.
It will re-order all pairs of keys and values based on the alphanumeric order of the values.
Then it will replace all keys with integer keys sequentially starting with 0.
So using sort() on arrays with integer keys (traditional index based array) is safe.
It is un-safe to use sort() on arrays with string keys (maps). Be careful.
Here is a PHP script on how to use sort():
<?php
$mixed = array();
$mixed["Zero"] = "PHP";
$mixed[1] = "Perl";
$mixed["Two"] = "Java";
$mixed["3"] = "C+";
$mixed[""] = "Basic";
$mixed[] = "Pascal";
$mixed[] = "FORTRAN";
sort($mixed);
print("Sorted by values:\n");
print_r($mixed);
?>
This script will print:
Sorted by values:
Array
(
[0] => Basic
[1] => C+
[2] => FORTRAN
[3] => Java
[4] => PHP
[5] => Pascal
[6] => Perl
)
(Continued on next part...)
Part:
1
2
3
4
5
6
7
|