


Detailed explanation of the use of php arrays Recommended_PHP tutorial
There are many array functions in PHP. The following is a summary of what I learned. I will write it down for future reference...
1. Array definition:
The definition of an array is defined using the array() method. , you can define an empty array:
.foreach traversal:
$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"), //End with a comma
"week"=>array ("Monday","Friday") //The last sentence has no punctuation
);
?>
2. Create an array:
Create The functions included in the array include compact(),
1. compact() function - convert one or more variables (including arrays) into arrays: array compact ( mixed $varname [, mixed $... ] ) 🎜>
$string = "I'm PHPer";
$array = array("And","You?");
$newArray = compact("number","string", "array");
print_r ($newArray);
?>
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.
Running results:
$array = array("I","Am","A","PHP","er");
$newArray = array_combine($number,$array);
print_r ($ newArray);
?>
Running results:
Array ( [1] => I [3 ] => Am [5] => A [7] => PHP [9] => er )
3. range() function - Create an array within a specified range: Not much to say Now, go directly to the example -
print_r($array1);
echo"
";
$array2 = range("A","Z");
print_r($array2);
echo "
";
$array3 = range("z","a");
print_r($array3);
?>
Running results:
4.array_fill()函数——填充数组函数:
$array = range(1,10);
$fillarray = range("a","d");
$arrayFilled = array_fill(0,5,$fillarray);//这里的$fillarray可以是字符串,如"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 "";
?>
运行结果:
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
)
三、数组的遍历:
1.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
2.while循环遍历:
while循环遍历一般结合list函数,以下是实例
$staff = array(
array("姓名","性别","年龄"),
array("小张","男",24),
array("小王","女",25),
array("小李","男",23)
);
echo "
$name | $sex | $age |
?>
运行结果:
姓名 | 性别 | 年龄 |
小张 | 男 | 24 |
小王 | 女 | 25 |
小李 | 男 | 23 |
$speed = range( 0,220,20);
for($i =0;$i
}
? >
Run result:
0 20 40 60 80 100 120 140 160 180 200 220
4. Array pointer operations:
Functions involved include reset, prev, end, next, current, each
Example 1:
$speed = range(0,220,20);
echo current($speed);//Output the value of the current position (at the beginning of the array)
$i = rand(1,11);
while($i--){
next($ speed);//Move the pointer one position backward from the current position
}
echo current($speed);//Output the value of the current position
echo "
";
echo prev($speed);//Output the previous position array value
echo "
";
echo reset($speed);//Reset the pointer of the array and point the pointer to Starting position
echo "
";
echo end($speed);//Output the array value of the last position
echo "
";
?>
Run result:
0220
200
0
220
Example 2: each function pointer operation
$speed = range(0,200,40);
echo "each moves the pointer down
";
echo "0 block The speed of 1st gear is ".current(each($speed))."
";
echo "The speed of 1st gear is ".current(each($speed))."
echo "The speed of 2nd gear is".current(each($speed))."
";
echo "The speed of 3rd gear is".current(each($ speed))."
";
echo "The speed of 4th gear is".current(each($speed))."
";
echo "5th gear The speed is ".current(each($speed))."
";
echo "Use each function to move the array pointer and perform array traversal
";
reset($speed);//This is to point the array pointer to the beginning of the array
while(list($key,$value)=each($speed)){
echo $key."=>" .$value."
";
}
?>
Running result:
each moves the pointer downwards
The speed of 0 gear is 0
The speed of 1st gear is 40
The speed of 2nd gear is 80
The speed of 3rd gear is 120
The speed of 4th gear 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. Add and delete operations of the array:
1. Add array members: Example 1: $num[] = value is directly assigned and appended to the end of the array:
$num = array(1=>80,2=>120,3=>160);
echo "use Expression adds array members
";
$num[]=240;
print_r($num);
?>
Running result:
Use expression to add array member Array ( [0] => 80 [1] => 120 [2] => 160 [3] => 240 )
Example 2: array_pad function, array Selective append to the beginning and end of the array
$num = array(1 =>80,2=>120,3=>160);
$num = array_pad($num,4,200);
echo "Use the array_pad function to add members to the end of the array
print_r($num);
echo "
array_pad can also fill the head of the array
";
$num = array_pad($num,-8 ,40);
print_r($num);
?>
Running result:
Use the array_pad function to add member Array to the end of the array ( [0] => 80 [1] => 120 [2] => 160 [3] => 200 ) array_pad can also fill the array Header Array ([0] => 40 [1] => 40 [2] => 40 [3] => 40 [4] => 80 [5] => 120 [6] => ; 160 [7] => 200 )
Example 3: Stack operation append (array_push):
$num = array(1=>80,2=>120,3=>160);
array_push($num ,200,240,280);//You can append by yourself, directly at the end of the array
print_r($num);
?>
Operating result:
Array ( [1] => 80 [2] => 120 [3] => 160 [4] => 200 [5] => 240 [6] => 280 )
Example 4: array_unshift() in Add array members at the beginning
$num = array(1= >80,2=>120,3=>160);
array_unshift($num,0,40);//You can append by 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: After using the array_unshift() function, the key value of the array will start from 0!
2. Delete array members:
Example 1: The unset() command deletes array members or arrays:
$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";
}
?>
Running 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
$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:
$a=array("red", "green", "blue", "yellow"," blue","green");
$result = array_unique($a);
print_r($result);
?>
Run result:
Array ( [0] => red [1] => green [2] => blue [3] => yellow )
Example 4: array_merge, array_merge_recursive merge arrays
$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 "";
$result = array_merge_recursive($array1,$array2,$array3,$array4,$array5);
echo "
";?>
print_r ($result);
echo "
Run result:
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
)
)
注:1.array_merge的键名是数字的将重新建立索引;遇到相同的字符串键名时,后面的将覆盖前面的。
2.array_merge_recursive函数的作用是将相同字符串的键名单元整合成一个数组。
六、数组的键值和值操作:
实例一:in_array()检测数组中是否有某个值存在
$array = range(0,9);
if(in_array(9,$array)){
echo "数组中存在";
}
?>
运行结果:
数组中存在
实例二:key()取得数组当前的键名:
$array = range(0,9);
$num = rand(0,8);
while($num--)
next($array);
$key = key($array);
echo $key;
?>
此实例结果为动态结果,范围(0-8),不做结果演示。
实例三:list()函数把数组中的值赋给指定变量:
$staff = array(
array("姓名","性别","年龄"),
array("小张","男",24),
array("小王","女",25),
array("小李","男",23)
);
echo "
$name | $sex | $age |
?>
运行结果:
实例四:array_flip()交换数组的键值和值:
$array = array("red","blue","yellow","Black");
print_r($array);
echo "
";
$array = array_flip($array);
print_r($array);
?>
运行结果:
Array ( [0] => red [1] => blue [2] => yellow [3] => Black )
Array ( [red] => 0 [blue] => 1 [yellow] => 2 [Black] => 3 )
实例五:array_keys()、array_values()返回数组中所有的键值和值:
$array = array("red","blue","yellow","Black");
$result = array_keys($array);
print_r($result);
echo "
";
$result = array_values($array);
print_r($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:
$array = array("red","blue","yellow","Black");
$result = array_search("red",$array);
if(($result === NULL)){
echo "The value red does not exist";
}else{
echo "The value $result exists";
}
?>
Result: There is a value 0
The value returned by the function array_search() may be false or 0 or NULL, so be careful to use "==="
7. Sorting of arrays:
Example 1 : sort(), rsort()/asort(), arsort() to sort the array:
$array = array("b","c","d","a");
sort($array);//Sort from low to high
print_r($array);
echo "
";
rsort($array);//Reverse sort
print_r($array);
?>
Result:
Array ( [0] => a [1] => b [2] => c [3] => d )
Array ( [0] => d [1] => c [2] => b [3] => a )
The sort() and rsort() functions sort the array from low to high, and the return result is bool value;
asort() and arsort() functions preserve the sorting of key values, and the key values are not re-indexed after sorting.
Example 2: Disturbing the order of the array - shuffle() function:
$array = array("a","b","c","d");
shuffle($array);//Sort from low to high
print_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:
< ?PHP
$array = array("d","b","a","c");
$array = array_reverse($array);//Sort from low to high
print_r ($array);
?>
Run result:
Array ( [0] => c [1] => a [2] => b [ 3] => d )
Example 4: Natural sorting algorithm - natsort() and natcasesort();
$array = array("sort2","Sort5","sort1","sort4");
natsort($array);//from low Sort 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 the array, which is the normal sorting using numbers algorithm. natcasesort ignores case.
Example 5: Sort arrays by key value ksort():
< ?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: ksort() function is re-established indexed.
8. Other uses of arrays:
cout($array) -------- Count the number of units in an array
array_diff($array1,$array2)------ --- Count the differences between arrays and return 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 two array key values
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!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

If you are an experienced PHP developer, you might have the feeling that you’ve been there and done that already.You have developed a significant number of applications, debugged millions of lines of code, and tweaked a bunch of scripts to achieve op

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.
