Php array usage details _ php tips-php Tutorial

Source: Internet
Author: User
Tags array definition
For Web programming, the most important thing is to access and read/write data. There may be many storage methods, such as strings, arrays, and files. I learned arrays today, which is an important method in PHP Data applications. PHP has a large number of array functions. The following is a summary of my learning, so that you can easily identify them later ......
I. array definition:
The array definition uses the array () method to define an empty array:
. Foreach traversal:

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"), // end with a comma
"Week" => array ("Monday", "Friday") // The last sentence contains no punctuation.
);
?>


2. create an array:
Create the functions included in the array: compact (),
1. compact () function -- convert one or more variables (including arrays) to an array: array compact (mixed $ varname [, mixed $...])

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 );
?>


The compact () function is used to convert two or more variables to an array. of course, it also contains array variables. The parameter is the variable name, not the $ full name.
The opposite function is extract (). as the name suggests, it is to convert an array into a single string. The key value is used as the string name, and the array value is used as the string value.
Running result:

The code is as follows:


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


2. array_combine () -- combines two arrays into an array, one as the key value and the other as the value: array array_combine (array $ keys, array $ values)

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 );
?>


No more about the array_combine function.
Running result:
Array ([1] => I [3] => Am [5] => A [7] => PHP [9] => er)
3. range () function -- create an array of the specified range: Let's not talk about it. go directly to the instance --

The code is as follows:


$ Array1 = range (0,100, 10); // 0 indicates the start value, 100 indicates the end value, and 10 indicates the step value (the default step value is 1 ).
Print_r ($ array1 );
Echo"
";
$ Array2 = range ("A", "Z ");
Print_r ($ array2 );
Echo"
";
$ Array3 = range ("z", "");
Print_r ($ array3 );
?>


The default step value of the range () function is 1!
Running result:

The code is as follows:


Array ([0] => 0 [1] => 10 [2] => 20 [3] => 30 [4] => 40 [5] => 50 [6] = & gt; 60 [7] = & gt; 70 [8] = & gt; 80 [9] = & gt; 90 [10] = & gt; 100) array ([0] => A [1] => B [2] => C [3] => D [4] => E [5] => F [6] => G [7] => H [8] => I [9] => J [10] => K [11] => L [12] => M [13] => N [14] => O [15] => P [16] => Q [17] => R [18] => S [19] => T [20] => U [21] => V [22] => W [23] => X [24] => Y [25] => Z) array ([0] => z [1] => y [2] => x [3] => w [4] => v [5] => u [6] => t [7] => s [8] => r [9] => q [10] => p [11] => o [12] => n [13] => m [14] => l [15] => k [16] => j [17] => I [18] => h [19] => g [20] => f [21] => e [22] => d [23] => c [24] => B [25] =>)


4. array_fill () function -- fill the array function:

The code is as follows:


$ Array = range (1, 10 );
$ Fillarray = range ("a", "d ");
$ ArrayFilled = array_fill (, $ fillarray); // $ fillarray can be a string, such as "test ".
Echo"

"; 
print_r ($arrayFilled);
echo "
";
$ Keys = array ("string", "2", 9, "SDK", "PK ");
$ Array2 = array_fill_keys ($ keys, "testing ");
Echo"
"; 
print_r ($array2);
echo "
";
?>


Running result:

The code is as follows:


Array
(
[0] => Array
(
[0] =>
[1] => B
[2] => c
[3] => d
)
[1] => Array
(
[0] =>
[1] => B
[2] => c
[3] => d
)
[2] => Array
(
[0] =>
[1] => B
[2] => c
[3] => d
)
[3] => Array
(
[0] =>
[1] => B
[2] => c
[3] => d
)
[4] => Array
(
[0] =>
[1] => B
[2] => c
[3] => d
)
)
Array
(
[String] => testing
[2] => testing
[9] => testing
[SDK] => testing
[PK] => testing
)


3. array traversal:
1. foreach traversal: foreach (array_expression as $ value ){}
Foreach (array_expression as $ key => $ value ){}
For example:

The code is as follows:


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


Running result:

The code is as follows:


0 => 50
1 => 120
2 => 180
3 => 240
4 => 380


2. while loop traversal:
While loop traversal is generally combined with the list function, the following is an instance

The code is as follows:


$ Staff = array (
Array ("name", "gender", "age "),
Array ("Xiao Zhang", "male", 24 ),
Array ("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
";
?>


Running result:
Name Gender Age
Xiao Zhang Male 24
John Female 25
Xiao Li Male 23
3. for loop traversal:

The code is as follows:


$ Speed = range (0,220, 20 );
For ($ I = 0; $ I Echo $ speed [$ I]. "";
}
?>


Running result:

The code is as follows:


0 20 40 60 80 100 120 140 160 180 200


4. array pointer operations:
Involved functions include reset, prev, end, next, current, and each.
Instance 1:

The code is as follows:


$ 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); // The pointer moves one digit backward from the current position
}
Echo current ($ speed); // output the value of the current position
Echo"
";
Echo prev ($ speed); // output the array value in the previous position
Echo"
";
Echo reset ($ speed); // reset the pointer to the starting position.
Echo"
";
Echo end ($ speed); // output the array value at the last position
Echo"
";
?>


Running result:

The code is as follows:


0220
200
0
220


Example 2: each function pointer operation

The code is as follows:


$ Speed = range (0,200, 40 );
Echo "each implement pointer move down
";
Echo "the speed of 0 blocks is". current (each ($ speed ))."
";
Echo "1 speed is". current (each ($ speed ))."
";
Echo "2 speed is". current (each ($ speed ))."
";
Echo "the speed of 3 blocks is". current (each ($ speed ))."
";
Echo "the speed of 4 blocks is". current (each ($ speed ))."
";
Echo "the speed of 5 blocks is". current (each ($ speed ))."
";
Echo "use the each function to move the array pointer and traverse the array
";
Reset ($ speed); // The array pointer points to the first part of the array.
While (list ($ key, $ value) = each ($ speed )){
Echo $ key. "=>". $ value ."
";
}
?>


Running result:

The code is as follows:


Each implements pointer moving down
The speed of 0 blocks is 0.
The speed of Block 1 is 40.
The speed of two blocks is 80.
The speed of 3 blocks is 120.
The speed of 4 blocks is 160.
The speed of the fifth gear is 200.
Use the each function to move the array pointer and traverse the array.
0 => 0
1 => 40
2 => 80
3 => 120
4 => 160
5 => 200.


5. array addition and deletion operations:
1. add an array member: instance 1: $ num [] = value to append the value directly to the end of the array:

The code is as follows:


$ Num = array (1 => 160 =>, 3 => );
Echo "using expressions to add array members
";
$ Num [] = 240;
Print_r ($ num );
?>


Running result:
Use an expression to add an Array member Array ([0] => 80 [1] => 120 [2] => 160 [3] => 240)
Example 2: array_pad function, which selectively appends the first and end of an array

The code is as follows:


$ Num = array (1 => 160 =>, 3 => );
$ 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 array header
";
$ Num = array_pad ($ num,-8, 40 );
Print_r ($ num );
?>


Running result:

The code is as follows:


Use the array_pad function to add a member Array ([0] => 80 [1] => 120 [2] => 160 [3] => 200) to the end of the Array) 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: append an inbound stack (array_push ):

The code is as follows:


$ Num = array (1 => 160 =>, 3 => );
Array_push ($ num, 200,240,280); // You can append it by yourself and add it directly to the end of the array.
Print_r ($ num );
?>


Running result:
Array ([1] => 80 [2] => 120 [3] => 160 [4] => 200 [5] => 240 [6] => 280)
Example 4: Add an array member at the beginning of array_unshift ()

The code is as follows:


$ Num = array (1 => 160 =>, 3 => );
Array_unshift ($ num,); // You can append the value by yourself and add it directly to the end of the array.
Print_r ($ num );
?>


Running result:
Array ([0] => 0 [1] => 40 [2] => 80 [3] => 120 [4] => 160)
Note: After the array_unshift () function is used, the key value of the array starts from 0!
2. delete array members:
Example 1: unset () command to delete an array member or array:

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 ";
}
?>


Running result: (the running error and description array are also deleted and no longer exist)

The code is as follows:


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: \ wamp \ www \ testing \ editorplus \ test. php on line 21
The unset command cannot delete the entire array.


Example 2: The array_splice () function deletes an array member.

The code is as follows:


$ A = array ("red", "green", "blue", "yellow ");
Count ($ a); // Get 4
Array_splice ($ a,); // deletes the second element.
Count ($ a); // Get 3
Echo $ a [2]; // obtain yellow
Echo $ a [1]; // Get blue
?>


Example 3: array_unique:

The code is as follows:


$ A = array ("red", "green", "blue", "yellow", "blue", "green ");
$ Result = array_unique ($ );
Print_r ($ result );
?>


Running result:
Array ([0] => red [1] => green [2] => blue [3] => yellow)
Example 4: array_merge and array_merge_recursive merge arrays

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"

"; 
print_r($result);
echo "
";
$ Result = array_merge_recursive ($ array1, $ array2, $ array3, $ array4, $ array5 );
Echo"
"; 
print_r ($result);
echo "
";
?>


Running result:

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 a number, the index will be re-created. if the same string key name is used, the subsequent key name will overwrite the previous one.
2. the array_merge_recursive function integrates the key list elements of the same string into an array.
VI. operation of the array key value and value:
Example 1: in_array () checks whether a value exists in the array.

The code is as follows:


$ Array = range (0, 9 );
If (in_array (9, $ array )){
Echo "exists in the array ";
}
?>


Running result:
Array exists
Example 2: key () gets the current key name of the array:

The code is as follows:


$ Array = range (0, 9 );
$ Num = rand (0, 8 );
While ($ num --)
Next ($ array );
$ Key = key ($ array );
Echo $ key;
?>


The result of this instance is a dynamic result in the range of (0-8) and is not displayed.
Example 3: The list () function assigns the values in the array to the specified variable:

The code is as follows:


$ Staff = array (
Array ("name", "gender", "age "),
Array ("Xiao Zhang", "male", 24 ),
Array ("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
";
?>


Running result:


Example 4: array_flip () swap the key value and value of the array:

The code is as follows:


$ Array = array ("red", "blue", "yellow", "Black ");
Print_r ($ array );
Echo"
";
$ Array = array_flip ($ array );
Print_r ($ array );
?>


Running result:

The code is as follows:


Array ([0] => red [1] => blue [2] => yellow [3] => Black)
Array ([red] => 0 [blue] => 1 [yellow] => 2 [Black] => 3)


Example 5: array_keys () and array_values () return all key values and values in the array:

The code is as follows:


$ Array = array ("red", "blue", "yellow", "Black ");
$ Result = array_keys ($ array );
Print_r ($ result );
Echo"
";
$ Result = array_values ($ array );
Print_r ($ result );
?>


Running result:

The code is as follows:


Array ([0] => 0 [1] => 1 [2] => 2 [3] => 3)
Array ([0] => red [1] => blue [2] => yellow [3] => Black)


Example 6: array_search () search value:

The code is as follows:


$ Array = array ("red", "blue", "yellow", "Black ");
$ Result = array_search ("red", $ array );
If ($ result = NULL )){
Echo "no value red ";
} Else {
Echo "value $ result ";
}
?>


Result: a value of 0 exists.
The value returned by the array_search () function may be false, 0, or NULL. therefore, be sure to use "=" when determining the value"
VII. sorting of arrays:
Example 1: sorting arrays by sort (), rsort ()/asort (), and arsort:

The code is as follows:


$ Array = array ("B", "c", "d", "");
Sort ($ array); // sort from low to high
Print_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] =>)
The sort () and rsort () functions sort arrays in ascending order and return bool values;
The asort () and arsort () functions retain the sorting of key values. after sorting, the key values are not re-indexed.
Example 2: disrupt the array order -- shuffle () function:

The code is as follows:


$ Array = array ("a", "B", "c", "d ");
Shuffle ($ array); // sort from low to high
Print_r ($ array );
?>


The result is dynamic:
Array ([0] => c [1] => a [2] => d [3] => B)
The shuffle result is a bit random, and each refresh is different.

Example 3: reverse direction of the array_reverse () array:

The code is as follows:


$ Array = array ("d", "B", "a", "c ");
$ Array = array_reverse ($ array); // sort from low to high
Print_r ($ array );
?>


Running result:
Array ([0] => c [1] => a [2] => B [3] => d)
Example 4: Natural sorting algorithms natsort () and natcasesort ();

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 () are used to sort arrays in a natural way. Natcasesort ignores case sensitivity.
Example 5: sort the key values of the array ksort ():

The code is as follows:


$ 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-creates an index.
8. other array usage:
Cout ($ array) -------- count the number of units in the array
Array_diff ($ array1, $ array2) ---------- calculate the differences between arrays, and return the results that are included in the first array but not in the second array.
Array_diff_assoc ($ array1, $ array2) --------- Same as array_diff (), but it only 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) ------------ sum of all values
Array_rand ($ array, $ n) ---------- in the $ array, get $ n values and return the array
Array_intersect ($ array1, $ array2) -------------- get the intersection of two arrays
Array_intersect_assoc ($ array1, $ array2) ------------- perform key value comparison based on array_intersect
Array_intersect_key ($ array1, $ array2) --------------- compare the intersection of the key values of the two arrays
Summary:
The use of arrays is crucial in PHP. because PHP does not have pointers, arrays undertake a large amount of data operation tasks. Learning arrays well can make PHP applications handy. all the functions and usage related to PHP arrays are listed here. please study them together!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.