This chapter describes several common internal functions of PHP arrays.
We have already introduced PHP arrays. Create an array using the array () function and delete an array element using the unset () function. In this section, we also need to learn some other common internal functions related to arrays.
Count, sizeof
Count-returns the number of elements in an array. Sizeof is the alias of count. Similar to count, sizeof returns the number of elements in an array.
The count function example is as follows. In the following example, the number of elements in the array is 6.
Copy codeThe Code is 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 keys of each element in the array also change due to sorting. An example of the sort function is as follows:Copy codeThe Code is as follows:
<Html>
<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 ($ );
Echo "after sorting: <br/> ";
Foreach ($ a as $ key => $ value)
{
Echo "a [$ key]: $ value <br/> ";
}
?>
</Body>
</Html>
The returned result is:
Copy codeThe Code is 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 and retains the original key of each element.
Change sort ($ a) in the above example to asort ($ a). The result is:
Copy codeThe Code is 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 based on the size of the key. An example of the ksort function is as follows:
Copy codeThe Code is as follows:
<Html>
<Body>
<? Php
$ Fruits = array ("d" => "lemon", "a" => "orange", "B" => "banana ", "c" => "apple ");
Ksort ($ fruits );
Foreach ($ fruits as $ key => $ val ){
Echo "$ key: $ val <br/> ";
}
?>
</Body>
</Html>
The returned results are as follows:
Copy codeThe Code is as follows:
A: orange
B: banana
C: apple
D: lemon