PHP common array internal function of Array Functions introduction

  • 2020-06-07 04:06:38
  • OfStack

This chapter describes several common PHP array internals.
We've already looked at PHP arrays, creating 1 array with the array() function and removing 1 array element with the unset() function. In this section we will also learn about some other common internal functions related to arrays.
count,sizeof
count - Returns the number of elements in an array. sizeof, an alias for count, functions like count 1 and returns the number of elements in an array.
An example of the count function is shown below, where the number of elements in the output array is 6.
 
<?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 each element of the array is changed. Examples of sort functions are 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($a); 
echo "after sorting: <br />"; 
foreach ($a as $key=>$value) 
{ 
echo "a[$key]: $value <br />"; 
} 
?> 
</body> 
</html> 

The display results returned are:
 
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 - Sort the elements of the array, leaving each element as key.
We changed sort($a) in the above example to asort($a) and got the following result:
 
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 key. Examples of ksort functions are 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 results returned are as follows:
 
a : orange 
b : banana 
c : apple 
d : lemon 

Related articles: