Home >Backend Development >PHP Tutorial >Summary of PHP array operations Tips on using php arrays_PHP tutorial

Summary of PHP array operations Tips on using php arrays_PHP tutorial

WBOY
WBOYOriginal
2016-07-21 15:26:08718browse

Arrays can be said to be one of the more important methods in PHP data applications. There are many array functions in PHP. The following is a summary of what I learned so that I can learn from them in the future.
1. Array definition
The definition of array is defined using array() method. You can define an empty array:

Copy code The code is as follows:

$number = array(1,3,5,7,9);
//Define an empty array
$result = array();
$color =array("red","blue","green");
//Custom key value
$language = (1=>"English",3=>"Chinese" ,5=>"Franch");
//Define a two-dimensional array
$two = array(
"color"=>array("red","blue"), //Use Comma ending
"week"=>array("Monday","Friday") //The last sentence has no punctuation
);
?>

2. Create Array
compact()
compact() function - Convert one or more variables (containing arrays) to an array: array compact ( mixed $varname [, mixed $... ] ).
Copy code The code is as follows:

$number = "1,3,5,7 ,9";
$string = "I'm PHPer";
$array = array("And","You?");
$newArray = compact("number","string" ,"array");
print_r ($newArray);
?>

compact() function is used to convert two or more variables into arrays, of course it also includes array variable. The parameter is the name of the variable rather than the full name with $. The opposite function is extract(). As the name suggests, it converts the array into a single string, with the key value as its string name and the array value as the string value.
Run result:
Copy code The code is as follows:

Array (
[number] => 1 ,3,5,7,9
[string] => I'm PHPer
[array] => Array ( [0] => And [1] => You? )
)

array_combine()
array_combine() - Reorganize two arrays into one array, one as the key value and the other as the value: array array_combine ( array $keys , array $values )
Copy code The code is as follows:

$number = array("1"," 3","5","7","9");
$array = array("I","Am","A","PHP","er");
$newArray = array_combine($number,$array);
print_r ($newArray);
?>

I won’t say much about the array_combine function, everyone will understand it after reading it.
Run result:
Array ( [1] => I [3] => Am [5] => A [7] => PHP [9] => er )
range()
range() function - creates an array within a specified range:
Copy code The code is as follows:
$array1 = range(0,100,10);//0 is the starting value, 100 is the end value, and 10 is the step value (the default step value is 1).
print_r($array1);
echo "
";
$array2 = range("A","Z");
print_r($array2);
echo "
";
$array3 = range("z","a");
print_r($array3);
?>

array_fill()
array_fill () function - fill array function:
Copy code The code is as follows:
$array = range( 1,10);
$fillarray = range("a","d");
$arrayFilled = array_fill(0,5,$fillarray);//$fillarray here can be a string, such as "test".
echo "
"; <br>print_r ($arrayFilled); <br>echo "
";
$keys = array("string","2 ",9,"SDK","PK");
$array2 = array_fill_keys($keys,"testing");
echo "
"; <br>print_r ($array2); <br>echo "
";
?>

Run result:
Copy code Code As follows:
Array
(
[0] => Array
(
[0] => a
[1] => b
[2] => c
[3] => d
)

[1] => Array
(
[0] => a
[1] => b
[2] => c
[3] => d
)

[2] => Array
(
[0] => a
[1] => b
[2] => c
[3] => d
)

[3] => Array
(
[0] => a
[1] => b
[2] => c
[3] => d
)

[4] => Array
(
[0] => a
[1] => b
[2] => c
[3] => d
)

)
Array
(
[string] => testing
[2] => testing
[9] => testing
[SDK] => testing
[PK] => testing
)

3. 数组的遍历
foreach遍历
foreach (array_expression as $value){}
foreach (array_expression as $key => $value){}
复制代码 代码如下:

$speed = array(50,120,180,240,380);
foreach($speed as $keys=>$values){
echo $keys."=>".$values."
";
}
?>

运行结果:
0=>50
1=>120
2=>180
3=>240
4=>380
while循环遍历
while循环遍历一般结合list函数,以下是实例
复制代码 代码如下:
$staff = array(
array("姓名","性别","年龄"),
array("小张","男",24),
array("小王","女",25),
array("小李","男",23)
);
echo "";
while(list($keys,$value) = each($staff)){
list($name,$sex,$age) = $value;
echo "";
}
echo "
$name$sex$age
";
?>

for循环遍历
复制代码 代码如下:
$speed = range(0,220,20);
for($i =0;$iecho $speed[$i]." ";
}
?>

运行结果:
0 20 40 60 80 100 120 140 160 180 200 220
4. 数组的指针操作
涉及函数包括reset、prev、end、next、current、each。
实例一:next 与 prev
复制代码 代码如下:
$speed = range(0,220,20);
echo current($speed);//输出当前位置的值(在数组的开头位置)
$i = rand(1,11);
while($i--){
next($speed);//指针从当前位置向后移动一位
}
echo current($speed);//输出当前位置的值
echo "
";
echo prev($speed);//输出前一位置数组值
echo "
";
echo reset($speed);//重置数组的指针,将指针指向起始位置
echo "
";
echo end($speed);//输出最后位置的数组值
echo "
";
?>

运行结果:
0220
200
0
220
实例二:each函数指针操作
复制代码 代码如下:
$speed = range(0,200,40);
echo "each实现指针下移
";
echo "0挡的速度是".current(each($speed))."
";
echo "1挡的速度是".current(each($speed))."
";
echo "2挡的速度是".current(each($speed))."
";
echo "3挡的速度是".current(each($speed))."
";
echo "4挡的速度是".current(each($speed))."
";
echo "5挡的速度是".current(each($speed))."
";
echo "使用each函数实现数组指针的移动,进行数组遍历
";
reset($speed);//这里是将数组指针指向数组首
while(list($key,$value)=each($speed)){
echo $key."=>".$value."
";
}
?>

运行结果:
复制代码 代码如下:
each realizes the pointer moving down
The speed of 0th gear is 0
The speed of 1st gear is 40
The speed of 2nd gear is 80
The speed of 3rd gear is 120
4th gear The speed is 160
The speed of 5th gear is 200
Use each function to move the array pointer and perform array traversal
0=>0
1=>40
2=> 80
3=>120
4=>160
5=>200
5. Array addition and deletion operations
Add array members
Example 1: $num[ ] = value is directly assigned and appended to the end of the array:
[code]$num = array(1=>80,2=>120,3=>160);
echo "Use expression to add array members
";
$num[]=240;
print_r($num);
?>

Running results:
Use expression to add array members
Array ( [0] => 80 [1] => 120 [2] => 160 [3] => 240 )
Example 2: array_pad function, selectively append the beginning and end of the array array
Copy the code The code is as follows:

$num = array(1=>80,2=>120,3=>160);
$num = array_pad($num,4,200);
echo "Use array_pad function to add to the end of the array Members
";
print_r($num);
echo "
array_pad can also fill the head of the array
";
$num = array_pad ($num,-8,40);
print_r($num);
?>

Run results:
Use the array_pad function to add members to the end of the array
Array ( [0] => 80 [1] => 120 [2] => 160 [3] => 200 )
array_pad can also fill the head of the array
Array ( [0] = > 40 [1] => 40 [2] => 40 [3] => 40 [4] => 80 [5] => 120 [6] => 160 [7] => ; 200 )
Example 3: Push operation to append (array_push):
Copy code The code is as follows:
$num = array(1=>80,2=>120,3=>160);
array_push($num,200,240,280);//You can append it yourself, directly at the end of the array
print_r($num);
?>

Run result:
Array ( [1] => 80 [2] => 120 [3] => ; 160 [4] => 200 [5] => 240 [6] => 280 )
Example 4: array_unshift() adds array members at the beginning
Copy the code The code is as follows:

$num = array(1=>80,2=>120,3=>160) ;
array_unshift($num,0,40);//You can append it yourself, directly at the end of the array
print_r($num);
?>

Run Result:
Array ( [0] => 0 [1] => 40 [2] => 80 [3] => 120 [4] => 160 )
Note: array_unshift( )The key value of the array will start from 0 after using the function!
Delete array members
Example 1: The unset() command deletes array members or arrays:
Copy code The code is as follows:
$num = array_fill(0,5,rand(1,10));
print_r($num);
echo "
";
unset($num[4]);
print_r($num);
echo "
";
unset($num);
if(is_array){
echo "The unset command cannot delete the entire array";
}else{
echo "The unset command can delete the array";
}
?>

Run Result: (Running error and description array are also deleted and no longer exist)
Array ( [0] => 9 [1] => 9 [2] => 9 [3] => 9 [ 4] => 9 )
Array ( [0] => 9 [1] => 9 [2] => 9 [3] => 9 )

Notice: Use of undefined constant is_array - assumed 'is_array' in H:wampwwwtestingeditorplustest.php on line 21
The unset command cannot delete the entire array
Example 2: array_splice() function deletes array members
Copy code The code is as follows:
$a=array("red", "green", "blue", "yellow");
count ($a); //Get 4
array_splice($a,1,1); //Delete the second element
count ($a); //Get 3
echo $a [2]; //Get yellow
echo $a[1]; //Get blue
?>

Example 3: array_unique deletes duplicate values ​​in the array:
Copy code The code is as follows:

$a=array("red", "green", "blue", "yellow","blue","green");
$result = array_unique($a);
print_r($result);
?>

Running results:
Array ( [0] => red [1] => green [2] => blue [3] => yellow )
Example 4: array_merge, array_merge_recursive merge Array
Copy code The code is as follows:
$array1 = array("r"=>"red ",1,2,3,4);
$array2 = array("b"=>"blue",4=>5,6,7,8,9);
$array3 = array("r"=>"read",4=>10,2=>11);
$array4 = array(
array(4=>10),
array( 7=>13)
);
$array5 = array(
array(4=>11),
array(6=>12)
);
$result = array_merge($array1,$array2,$array3,$array4,$array5);
echo "
"; <br>print_r($result); <br>echo "</pre&gt ;"; <br>$result = array_merge_recursive($array1,$array2,$array3,$array4,$array5); <br>echo "<pre class="brush:php;toolbar:false">"; <br>print_r ($result); <br> echo "
";
?>

Run result:
Copy code The code is as follows:
Array
(
[r] => read
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[b] => blue
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
[9] => 10
[10] => 11
[11] => Array
(
[4] => 10
)

[12] => Array
(
[7] => 13
)

[13] => Array
(
[4] => 11
)

[14] => Array
(
[6] => 12
)

)
Array
(
[r] => Array
(
[0] => red
[1] => read
)

[0] => 1
[1] => 2
[2] => 3
[3] => 4
[b] => blue
[4] => 5
[5] => 6
[6] => 7
[7] => 8
[8] => 9
[9] => 10
[10] => 11
[11] => Array
(
[4] => 10
)

[12] => Array
(
[7] => 13
)

[13] => Array
(
[4] => 11
)

[14] => Array
(
[6 ] => 12
)

)

Note: 1. If the key name of array_merge is numeric, the index will be re-established; when the same string key name is encountered , the later ones will overwrite the previous ones. 2. The function of array_merge_recursive function is to integrate the key name units of the same string into an array.
6. Array key and value operations
Example 1: in_array() detects whether a certain value exists in the array
Copy code The code is as follows:

$array = range(0,9);
if(in_array(9,$array)){
echo "in array Exists";
}
?>

Running result:
exists in the array. Example 2: key() gets the current key name of the array:
Copy code The code is as follows:

$array = range(0,9);
$num = rand (0,8);
while($num--)
next($array);
$key = key($array);
echo $key;
?>

The results of this example are dynamic results, range (0-8), and no result demonstration is performed.
Example 3: The list() function assigns the values ​​in the array to the specified variable:
Copy code The code is as follows:
< ;?PHP
$staff = array(
array("Name","Gender","Age"),
array("Xiao Zhang","Male",24),
array ("Xiao Wang", "Female", 25),
array("Xiao Li", "Male", 23)
);
echo "";
while(list($keys,$value) = each($staff)){
list($name,$sex,$age) = $value;
echo "";
}
echo "
$name$sex$age
";
?>

Example 4: array_flip() exchanges the key and value of the array:
Copy code The code is as follows :

$array = array("red","blue","yellow","Black");
print_r($array);
echo "
";
$array = array_flip($array);
print_r($array);
?>

Run result:
Array ( [0] => red [1] => blue [2] => yellow [3] => Black )
Array ( [red] => ; 0 [blue] =>
$array = array("red","blue","yellow","Black"); $result = array_keys($array); print_r($result); echo "
";
$result = array_values($array);
print_r($result);
?>


Run result:
Array ( [0] => 0 [1] => 1 [2] => 2 [3] => 3 )
Array ( [0] => red [1] => blue [2] => yellow [3] => Black )
Example 6: array_search() search value:


Copy the code

The code is as follows:

$array = array("red","blue","yellow","Black"); $result = array_search("red",$array); if(($result === NULL)){ echo "The value red does not exist";
}else{
echo "There is a value $result";
}
?>


Result: There is a value 0
The value returned by the function array_search() may be false or 0 or NULL, Therefore, be careful to use "==="
7. Sorting of arrays
Example 1: sort(), rsort()/asort(), arsort() to sort arrays:


Copy code

The code is as follows:

$array = array("b","c","d" ,"a"); sort($array);//Sort from low to highprint_r($array); echo "
";
rsort($ array);//Reverse sorting
print_r($array);
?>


Result:
Array ( [0] => a [1] => ; b [2] => c [3] => d )
Array ( [0] => d [1] => c [2] => b [3] => a )
sort() and rsort() functions sort the array from low to high, and the return result is a bool value;
asort() and arsort() functions preserve key values, and the key values ​​are sorted after sorting No reindexing.
Example 2: Disturbing the order of the array - shuffle() function:



Copy code

The code is as follows:

$array = array("a","b","c","d"); shuffle($array);//Sort from low to highprint_r( $array); ?>

The result is a dynamic result:
Array ( [0] => c [1] => a [2] => d [3] => b)
The result of shuffle is a bit random and different every time it is refreshed.
Example 3: array_reverse() array reverse:


Copy code

The code is as follows:

$array = array("d","b","a","c"); $array = array_reverse($array);//Sort from low to highprint_r($array ); ?>

Run result:
Array ( [0] => c [1] => a [2] => b [3] = > d )
Example 4: Natural sorting algorithm - natsort() and natcasesort();


Copy code

The code is as follows:

$array = array("sort2","Sort5","sort1","sort4"); natsort($array);//Sort from low to high print_r($array); echo "
";
natcasesort($array);
print_r($array);
?>


Result:
Array ( [1] => Sort5 [2] => sort1 [0] => sort2 [3] => sort4 )
Array ( [2] = > sort1 [0] => sort2 [3] => sort4 [1] => Sort5 )
natsort() and natcasesort() perform natural sorting on arrays, which is the normal sorting algorithm using numbers. natcasesort ignores case.
Example 5: Sort array by key value ksort():


Copy code

The code is as follows:

< ?PHP $array = array(1=>"sort2",4=>"Sort5",2=>"sort1",3=>"sort4"); ksort($array );//Sort from low to high print_r($array); ?>

Result:
Array ( [1] => sort2 [2] => sort1 [3] => sort4 [4] => Sort5 )
Note: The ksort() function re-indexes.
8. Other uses of arrays


Copy code

The code is as follows:

cout($array) -------- Count the number of cells in the array
 array_diff($array1,$array2)----------Count the number of cells in the array The difference is that it returns what is in the first array but not in the second array.
 array_diff_assoc($array1,$array2)---------Same as array_diff(), except that it also compares key values
 array_diff_key($array1,$array2)---------- -----Compare key values
 array_product($array)-----------Return the product of all numbers in the array
 array_sum($array)-------- ------The sum of all values
 array_rand($array,$n)----------Take out $n values ​​​​in the $array array and return the array
 array_intersect($ array1,$array2)----------------Get the intersection of two arrays
 array_intersect_assoc($array1,$array2)------------ ---Compare key values ​​based on array_intersect
 array_intersect_key($array1,$array2)-----------------Compare the intersection of key values ​​of two arrays

Summary
The use of arrays is crucial in PHP. Since PHP does not have pointers, arrays bear a large number of data manipulation tasks. Only by learning arrays well can you apply PHP with ease. Listed here are the commonly used functions and usage related to PHP arrays. Welcome to learn together!

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/324006.htmlTechArticleArrays can be said to be one of the more important methods in PHP data applications. There are many array functions in PHP. The following is a summary of what I learned so that I can learn from them in the future. 1. Array definition Array...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn