This chapter describes several common internal functions of the PHP array.
In the previous we have introduced the PHP array, created an array with the arrays () function, deletes an array element with the unset () function. In this chapter we will also learn some other common internal functions about arrays.
count,sizeof
Count-Returns the number of elements in an array. sizeof is the alias for Count, which is the same as count, and the number of elements that return an array.
The Count function is shown, for example, in the following example, the number of elements in the output array is 6.
Copy Code code as follows:
<?php
$a = array (1,2,4,5,3,9);
echo count ($a); 6
?>
Sort
Sort-sorts the elements of an array. After sorting, the original key of the array elements is also changed because of the sort. The sort function example is as follows:
Copy Code code as follows:
<body>
<?php
$a = array (1,2,4,5,3,9);
echo "before sorting: <br/>";
foreach ($a as $key => $value)
{
echo "a[$key]: $value <br/>";
}
Sort ($a);
echo "After sorting: <br/>";
foreach ($a as $key => $value)
{
echo "a[$key]: $value <br/>";
}
?>
</body>
The returned display results are:
Copy Code code as follows:
Before sorting:
A[0]: 1
A[1]: 2
A[2]: 4
A[3]: 5
A[4]: 3
A[5]: 9
After sorting:
A[0]: 1
A[1]: 2
A[2]: 3
A[3]: 4
A[4]: 5
A[5]: 9
Asort
Asort-Sorts the elements of an array, preserving the original key of each element.
We change the sort ($a) in the example above to Asort ($a), and we get the result:
Copy Code code as follows:
Before sorting:
A[0]: 1
A[1]: 2
A[2]: 4
A[3]: 5
A[4]: 3
A[5]: 9
After sorting:
A[0]: 1
A[1]: 2
A[4]: 3
A[2]: 4
A[3]: 5
A[5]: 9
Ksort
Ksort-Sorts each element of the array according to the size of the key. The Ksort function example is as follows:
Copy Code code as follows:
<body>
<?php
$fruits = Array ("D" => "Lemon", "a" => "Orange", "B" => "banana", "C" => "Apple");
Ksort ($fruits);
foreach ($fruits as $key => $val) {
echo "$key: $val <br/>";
}
?>
</body>
The results returned are as follows:
Copy Code code as follows:
A:orange
B:banana
C:apple
D:lemon