


PHP array usage tips and operation summary, PHP array usage tips_PHP tutorial
php array usage skills and operation summary, php array usage skills
Arrays can be said to be one of the more important methods in PHP data applications. There are many array functions in PHP. Here are some summaries to remember them for future reference.
1. Array definition
Usage of array definition
Defined in array() method, you can define an empty array:
$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 comma
"week"=>array("Monday","Friday") //The last sentence has no punctuation
);
?>
2. Create array
compact()
compact() function - converts one or more variables (including arrays) into arrays: array compact ( mixed $varname [,
mixed $... ] ).
$number = "1,3,5,7,9";
$string = "I'm PHPer";
$array =
array("And","You?");
$newArray = compact("number","string","array");
print_r ($newArray);
?>
The compact() function is used to convert two or more variables into arrays, including array variables of course. 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 results:
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 )
$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 go into details 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:
$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:
$array = range(1,10);
$fillarray = range("a","d");
$arrayFilled =
array_fill(0,5,$fillarray);//$fillarray here can be a string, such as "test".
echo
"
1 |
|
$keys = array("string","2",9,"SDK","PK");
$array2 = array_fill_keys($keys,"testing");
echo "
1 2 |
|
?>
Run result:
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. Array traversal
foreach traversal
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."
";
}
?>
Run result:
0=>50
1=>120
2=>180
3=>240
4=>380
while loop traversal
While loop traversal is generally combined with the list function. The following is an example
$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 |
?>
for loop traversal
$speed = range(0,220,20);
for($i =0;$i
}
?>
Run results:
0 20 40 60 80 100 120 140 160 180 200 220
4. Array pointer operations
Involved functions include reset, prev, end, next, current, and each.
Example 1: next and prev
$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 the starting position
echo "
";
echo end($speed);//Output the array value of the last position
echo "
";
?>
Running results:
0220
200
0
220
Example 2: each function pointer operation
$speed = range(0,200,40);
echo "each moves the pointer down
";
echo "The speed of 0 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 "The speed of 5th gear is".current(each($speed))."
";
echo "Use each function to move the array pointer and perform array traversal
";
reset($speed);//Here is to point the array pointer to the beginning of the array
while(list($key,$value)=each($speed)){
echo $key."=>".$value."
";
}
?>
Operating results:
each realizes the pointer moving down
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. 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 expressions to add array members
";
$num[]=240;
print_r($num);
?>
Run result:
Use expression to add array members
Array ( [0] => 80
[1] => 120 [2] => 160 [3] => 240 )
Example 2: array_pad function, selective appending of the beginning and end of an 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);
?>
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 append (array_push):
$num = array(1=>80,2=>120,3=>160);
array_push($num,200,240,280);//You can add 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
$num =
array(1=>80,2=>120,3=>160);
array_unshift($num,0,40);//You can add 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: After using the array_unshift() function, the key value of the array will start from 0!
Delete array members
Example 1: The unset() command deletes array members or arrays:
Copy the 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 arrays";
}
?>
Run result: (Run 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 "
1 2 |
|
$result = array_merge_recursive($array1,$array2,$array3,$array4,$array5);
echo "
1 |
|
?>
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 one will overwrite the previous one. 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
$array = range(0,9);
if(in_array(9,$array)){
echo "Exists in array";
}
?>
Run result: Exists in array
Example 2: key() gets the current key name of the array:
$array = range(0,9);
$num =
rand(0,8);
while($num--)
next($array);
$key = key($array);
echo
$key;
?>
The result of this example is a dynamic result, the range is (0-8), and no result demonstration is performed.
Example 3: The list() function assigns the values in the array to the specified variable:
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:
$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] => 1
[yellow] => 2 [Black] => 3 )
$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:
$array =
array("red","blue","yellow","Black");
$result = array_search("red",$array);
if(($result === NULL)){
echo "There is no value red";
}else{
echo "There is a value red"
$result";
}
?>
Result: Value 0 exists
The value returned by the function array_search() may be false or 0 or NULL, so be careful to use "===" when making judgments
7. Sorting of arrays
Example 1: sort(), rsort()/asort(), arsort() to sort arrays:
$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 a bool value;
The 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 it is different every time it is refreshed.
Example 3: array_reverse() array reverse:
$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);//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 the array by key value ksort():
$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
cout($array) -------- Count the number of cells in the array
array_diff($array1,$array2)----------counts the differences between arrays and 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)----------Returns the product of all numbers in the array
array_sum($array)--------------The sum of all values
array_rand($array,$n)----------Take out $n values from the $array array and return the array
array_intersect($array1,$array2)----------------Get the intersection of two arrays
array_intersect_assoc($array1,$array2)---------------in array_intersect
Perform key-value comparison on the basis of
array_intersect_key($array1,$array2)-----------------Compare the intersection of two array key values

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











How to convert a php array from two dimensions to a one-dimensional array: 1. Use loop traversal to traverse the two-dimensional array and add each element to the one-dimensional array; 2. Use the "array_merge" function to merge multiple arrays into An array. Pass the two-dimensional array as a parameter to the "array_merge" function to convert it into a one-dimensional array; 3. Using the "array_reduce" function, you can process all the values in the array through a callback function and finally return a result.

In PHP programming, the array_sum function is a very practical function that can calculate the sum of all elements in an array. However, when we need to calculate the sum of a column of elements in a two-dimensional array, we may encounter some trouble. This article will introduce how to use the array_sum function in PHP to calculate the sum of elements in a column of a two-dimensional array. First, we need to understand the concept of two-dimensional arrays. A two-dimensional array is an array containing multiple arrays, which can be regarded as a table. Each array represents a table

How to reverse a two-dimensional array in php: 1. Create a php sample file; 2. Define a two-dimensional array; 3. Reverse the array through the "array_reverse($a,true);" function; 4. Use "print_r" to print Just reverse the two-dimensional array.

In PHP programming, we often need to operate on arrays, including obtaining the value of a specified column. PHP provides a very convenient function - array_column, which can help us quickly obtain the value of a specified column in a two-dimensional array. This article will introduce how to use the array_column function. Basic usage of array_column function: array_column(array$array,mixed$column_key[

How to convert a two-dimensional array to a one-dimensional array in PHP In PHP development, you often encounter scenarios where you need to convert a two-dimensional array into a one-dimensional array. This article will introduce several common methods to help you complete this task easily. Method 1: Use loop traversal The simplest and most straightforward method is to use a loop to traverse a two-dimensional array and add each element to a new one-dimensional array. Here is a code example using this method: functionflattenArray($array){$result

Detailed explanation of PHP5.5 functions: How to use the array_column function to extract a certain column in a two-dimensional array. In the PHP5.5 version, the array_column function was introduced. It is a very practical function that can extract a specified column of data from a two-dimensional array. This comes in handy when working with large amounts of data, allowing us to quickly get the data we need. The basic syntax of the array_column function is as follows: arrayarray_column(array$

PHP has a two-dimensional array, which is a special type of array that can store other arrays as elements. The declaration and access of a two-dimensional array are very simple. You can use the "array" function to create a two-dimensional array and use indexing or association. Arrays, as their elements, are very useful in practical programming and can be used to process various complex data structures.

Question Write a C program that uses runtime compilation to calculate the sum and product of all elements in a two-dimensional array. Solution runtime compilation or initialization is also known as dynamic allocation. Allocating memory at execution time (runtime) is called dynamic memory allocation. The functions calloc() and malloc() support dynamic memory allocation. The functions calloc() and malloc() support dynamic memory allocation. p>In this program, we will calculate the sum of all elements of a 2D array and the product of all elements at runtime. Logic is used to calculate the sum of all elements in a 2D array - printf("Sumarrayis:");for(i=0;i<2;i++){&
