PHP Array action Function Learning notes

Source: Internet
Author: User
Tags array definition arrays compact int size mixed prev rand shuffle


For Web programming, the most important thing is to access and read and write data. There may be many ways to store them, such as strings, arrays, files, and so on. arrays, which can be said to be a more important way of using PHP data. PHP's Array function is numerous, below is my study summary, takes this to remember, facilitates later to learn.
. Array definition
the definition of an array is defined using the array () method, and an empty array can be defined:


The code is as follows

<?php
$number = Array (1,3,5,7,9);
Define an empty array
$result = Array ();
$color =array ("Red", "Blue", "green");
Custom Key values
$language = (1=> "中文版",3=> "Chinese",5=> "Franch");
Defining two-dimensional arrays
$two = Array (
"Color" =>array ("Red", "blue"),//ending with a comma
"Week" =>array ("Monday", "Friday")//last sentence without punctuation
);
?>


2. Create an array
Compact ()
Compact () function-converts one or more variables (including arrays) to an array: the array compact (mixed $varname [, mixed $ ...]).


The code is as follows

? Php
$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, and, of course, to include arrays of variables. The argument is the name of the variable, not the full name. The opposite function is the extract () function that converts an array to a single string, a key value as its string name, and an array value as the value of the string.
Run Result:



Array (
[Number] => 1,3,5,7,9
[string] => I ' m phper
[Array] => array ([0] => and [1] => you?)
)



Array_combine ()
Array_combine ()--resets two arrays into an array, one for key values: Array array_combine (array $keys, array $values)


The code is as follows

? Php
$number = Array ("1", "3", "5", "7", "9");
$array = Array ("I", "Am", "A", "PHP", "er");
$newArray = Array_combine ($number, $array);
Print_r ($newArray);
?>


Array_combine function is not much said, who read all understand.
Run Result:
Array ([1] => I [3] => Am [5] => A [7] => PHP [9] => er)
Range ()
Range () function--Creates an array of the specified range:


The code is as follows
? Php
$array 1 = range (0,100,10);//0 is the starting value, 100 is the ending value, 10 is the step value (the default step value is 1).
Print_r ($array 1);
echo "<br/>";
$array 2 = Range ("A", "Z");
Print_r ($array 2);
echo "<br/>";
$array 3 = range ("Z", "a");
Print_r ($array 3);
?>


Array_fill ()
Array_fill () function--Populate array functions:


The code is as follows
? Php
$array = range (1,10);
$fillarray = Range ("A", "D");
$arrayFilled = Array_fill (0,5, $fillarray);//The $fillarray here can be strings, such as "test".
echo "<pre>";
Print_r ($arrayFilled);
echo "</pre>";
$keys = Array ("string", "2", 9, "SDK", "PK");
$array 2 = Array_fill_keys ($keys, "testing");
echo "<pre>";
Print_r ($array 2);
echo "</pre>";
?>


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. Traversal of arrays
foreach Traversal
foreach (array_expression as $value) {}
foreach (array_expression as $key => $value) {}


The code is as follows

? Php
$speed = Array (50,120,180,240,380);
foreach ($speed as $keys => $values) {
echo $keys. " => ". $values." <br/> ";
}
?>


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 instance


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 "<table border=2>";
while (the list ($keys, $value) = each ($staff)) {
List ($name, $sex, $age) = $value;
echo "<tr><td> $name </td><td> $sex </td><td> $age </td></tr>";
}
echo "</table>";
?>


For loop traversal


The code is as follows
? Php
$speed = range (0,220,20);
for ($i =0; $i <count ($speed); $i + +) {
echo $speed [$i]. " ";
}
?>


Run Result:
0 20 40 60 80 100 120 140 160 180 200-220
4. Pointer operation of Array
The involved functions include reset, prev, end, next, current, each.
Example one: Next and prev


The code is as follows
? Php
$speed = range (0,220,20);
Echo current ($speed);//Output the value at the position (at the beginning of the array)
$i = rand (1,11);
while ($i-) {
Next ($speed);//The pointer moves backward from the current position
}
Echo current ($speed);//Output The value of the present position
echo "<br/>";
Echo prev ($speed);//Output previous position array value
echo "<br/>";
echo Reset ($speed);//Reset the pointer to the array, pointing to the starting position
echo "<br/>";
Echo End ($speed);//Output The array value of the last position
echo "<br/>";
?>


Run Result:
0220
200
0
220
Example two: Each function pointer operation


  code is as follows
<"? PHP
$speed = range (0,200,40);
echo "Each implementation pointer moves down <br/>"; The
Echo 0-block speed is ". Current (each ($speed))." <br/> "; The
Echo 1-block speed is ". Current (each ($speed))." <br/> "; The
Echo 2-block speed is ". Current (each ($speed))." <br/> "; The
Echo 3-block speed is ". Current (each ($speed))." <br/> "; The
Echo 4-block speed is ". Current (each ($speed))." <br/> "; The
Echo 5-block speed is ". Current (each ($speed))." <br/> ";
Echo uses the each function to move the array pointer to the array traversal <br/> ";
Reset ($speed);//This is to point the array pointer to the array first
while ($key, $value) =each ($speed)) {
echo $key. => ". $value." <br/> ";
}
?>


Run Result:
Each implementation pointer moves down
0 Gear speed is 0.
1 gear speed is 40.
2 gear speed is 80.
3 Gear speed is 120.
4 Gear speed is 160.
5 gear speed is 200.
Using the each function to move the array pointer, array traversal
0=>0
1=>40
2=>80
3=>120
4=>160
5=>200
5. Array additions and deletions operation
Add array members
Instance one: $num [] = value Direct assignment appended to the end of the array:
[Code


The code is as follows
]<? Php
$num = Array (1=>80,2=>120,3=>160);
echo "adds an array member <br/> using an expression";
$num []=240;
Print_r ($num);
?>


Run Result:
To add an array member using an expression
Array ([0] => [1] => [2] => 160 [3] => 240)
Example two: Array_pad function, array array and optional append


The code is as follows

? Php
$num = Array (1=>80,2=>120,3=>160);
$num = Array_pad ($num, 4,200);
Echo uses the Array_pad function to add members <br/> to the tail of the array;
Print_r ($num);
echo "<br/>array_pad can also populate array header <br/>";
$num = Array_pad ($num, -8,40);
Print_r ($num);
?>


Run Result:
To add a member to the tail of an array using the Array_pad function
Array ([0] => [1] => [2] => 160 [3] => 200)
Array_pad can also populate the array header
Array ([0] => [1] => [2] => [3] => [4] => [5] => [6] => 160 [7] => 200)
Example three: Stack operation append (Array_push):


The code is as follows


? Php
$num = Array (1=>80,2=>120,3=>160);
Array_push ($num, 200,240,280);//Can be appended directly to the end of the array
Print_r ($num);
?>


Run Result:
Array ([1] => [2] => [3] => 160 [4] => [5] => [6] => 280)
Example four: Array_unshift () Adding an array member at the beginning


The code is as follows

? Php
$num = Array (1=>80,2=>120,3=>160);
Array_unshift ($num, 0,40);//Can be appended directly to the end of the array
Print_r ($num);
?>


Run Result:
Array ([0] => 0 [1] => [2] => [3] => (4) => 160)
Note: the Array_unshift () function uses the key value of the following array to start at 0!
To subtract an array member
Instance one: unset () command deletes an array member or array:


The code is as follows
? Php
$num = Array_fill (0,5,rand (1,10));
Print_r ($num);
echo "<br/>";
Unset ($num [4]);
Print_r ($num);
echo "<br/>";
Unset ($num);
if (Is_array) {
echo "unset command cannot delete entire array";
}else{
echo "unset command can delete array";
}
?>


Run Result: (Run error and description array also deleted, no longer exists)
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
Instance two: Array_splice () function to delete an array member


The code is as follows
<?php
$a =array ("Red", "green", "blue", "yellow");
Count ($a); Get 4
Array_splice ($a, 1, 1); Delete a second element
Count ($a); Get 3
echo $a [2]; Get Yellow
echo $a [1]; Get Blue
?>


Instance three: Array_unique deletes duplicate values from the array:


The code is as follows

<?php
$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 four: Array_merge, array_merge_recursive merging arrays


  code is as follows
<?php
$array 1 = Array (" R "=>" Red ", 1,2,3,4);
$array 2 = Array ("B" => "Blue", 4=>5,6,7,8,9);
$array 3 = Array ("R" => "read", 4=>10,2=>11);
$array 4 = array (
Array (4=>10),
Array (7=>13)
);
$array 5 = array (
Array (4=>11),
Array (6=>12)
);
$result = Array_merge ($array 1, $array 2, $array 3, $array 4, $array 5);
echo "<pre>";
Print_r ($result);
echo "</pre>";
$result = array_merge_recursive ($array 1, $array 2, $array 3, $array 4, $array 5);
echo "<pre>";
Print_r ($result);
echo "</pre>";
?>


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
[Ten] => 11
[One] => Array
(
[4] => 10
)



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



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



[=>] 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
[Ten] => 11
[One] => Array
(
[4] => 10
)



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



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



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



)



Note: 1. Array_merge the key name of a number will be indexed again, and when the same string key name is encountered, the following will overwrite the previous one. 2. The role of the array_merge_recursive function is to synthesize an array of key list elements of the same string.
6. Array key value and value operation
Instance one: In_array () detects whether a value exists in the array


The code is as follows

<?php
$array = range (0,9);
if (In_array (9, $array)) {
echo "exists in array";
}
?>


Run Result: the array exists
Instance two: Key () Gets the current key name of the array:


The code is as follows

<?php
$array = range (0,9);
$num = rand (0,8);
while ($num--)
Next ($array);
$key = key ($array);
Echo $key;
?>


This instance results in a dynamic result, a range (0-8), and does not demonstrate the results.
Example three: the list () function assigns the value in the array to the specified variable:


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 "<table border=2>";
while (the list ($keys, $value) = each ($staff)) {
List ($name, $sex, $age) = $value;
echo "<tr><td> $name </td><td> $sex </td><td> $age </td></tr>";
}
echo "</table>";
?>


Instance four: Array_flip () Exchange the key values and values of the array:


The code is as follows

? Php
$array = Array ("Red", "blue", "yellow", "black");
Print_r ($array);
echo "<br/>";
$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)


The code is as follows

? Php
$array = Array ("Red", "blue", "yellow", "black");
$result = Array_keys ($array);
Print_r ($result);
echo "<br/>";
$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 six: Array_search () Search values:


The code is as follows

? Php
$array = Array ("Red", "blue", "yellow", "black");
$result = Array_search ("Red", $array);
if (($result = = NULL)) {
echo "does not exist a value red";
}else{
echo "exists numerical $result";
}
?>


Result: There is a value of 0
The value returned by the function Array_search () may be false or 0 or null, so be careful to use "= = =" When judging
7. Ordering of arrays
Instance one: Sort (), Rsort ()/asort (), Arsort () array of arrays:


The code is as follows

? Php
$array = Array ("B", "C", "D", "a");
Sort ($array);//from Low to high
Print_r ($array);
echo "<br/>";
Rsort ($array);//Reverse Ordering
Print_r ($array);
?>


Results:
Array ([0] => a [1] => b [2] => C [3] => D)
Array ([0] => D [1] => C [2] => b [3] => a)
The sort (), rsort () function is sorted from low to high, and the result is bool;
The Asort (), Arsort () function is the sort that preserves the key values, and the key values are not indexed again after sorting.
Example two: Upsetting the array order--shuffle () function:


The code is as follows

? Php
$array = Array ("A", "B", "C", "D");
Shuffle ($array);//from Low to high order
Print_r ($array);
?>


Results are dynamic results:
Array ([0] => C [1] => a [2] => D [3] => B)
The results of shuffle are somewhat random, and each refresh is different.
Example three: Array_reverse () array Reverse:


The code is as follows

? Php
$array = Array ("D", "B", "A", "C");
$array = Array_reverse ($array);//from low to high sort
Print_r ($array);
?>


Run Result:
Array ([0] => C [1] => a [2] => b [3] => D)
Example four: Natural sorting algorithm--natsort () and Natcasesort ();


The code is as follows

? Php
$array = Array ("Sort2", "Sort5", "Sort1", "sort4");
Natsort ($array);//from Low to high order
Print_r ($array);
echo "<br/>";
Natcasesort ($array);
Print_r ($array);
?>


Results:
Array ([1] => Sort5 [2] => sort1 [0] => Sort2 [3] => Sort4)
Array ([2] => sort1 [0] => Sort2 [3] => sort4 [1] => Sort5)
Natsort (), Natcasesort () is a natural sort of array, using the normal sorting algorithm of numbers. Natcasesort ignores case.
Instance five: Array of key values sort Ksort ():


The code is as follows

? Php
$array = Array (1=> "Sort2",4=> "Sort5",2=> "Sort1",3=> "Sort4");
Ksort ($array);//from Low to high order
Print_r ($array);
?>


Results:
Array ([1] => Sort2 [2] => Sort1 [3] => SORT4 [4] => Sort5)
Note: the Ksort () function has been indexed again.



8. Other uses of arrays



$


The code is as follows

Array = array (' A ', ' B ', ' C ');
Use int array_unshift (array $array, mixed variable[,mixed variable ...]) Add an element to the array header
Array_unshift ($array, ' E ', ' F ', ' G ');
Var_dump ($array);

$array = Array (' A ', ' B ', ' C ');
Use int Array_push (array $array, mixed variable[,mixed variable ...]) Add an element at the end of an array
Array_push ($array, ' E ', ' F ', ' G ');
Var_dump ($array);

$array = Array (' A ', ' B ', ' C ');
To delete an element in an array header using mixed Array_shift (array $array)
Array_shift ($array);
Var_dump ($array);

$array = Array (' A ', ' B ', ' C ');
Delete an element at the end of an array using mixed Array_pop (array $array)
Array_pop ($array);
Var_dump ($array);




/*


* Search for a specific value in the array and return FALSE if found return True


* Boolean In_array (mixed Needle,array Haystack[,boolean Strict))


* Find a specified health in the array and return FALSE if found return True


* Boolean array_eky_exists (mixed Key,array array)


* Search for a specific value in the array and return FALSE if found return True


* Boolean array_search (mixed Needle,array Haystack[,boolean Strict))


* Gets a new array of all the keys in the array


* Array Array_keys (array array[,mixed search_value])


* Gets a new array of all the values of the array


* Array array_values (array array)


* Determine the size of the array


* Integer count (array array[,int mode])


* Integer sizeof (array array[,int mode])


* Statistical array element Occurrence frequency


* Array array_count_values (array array)


* Deletes duplicate values in an array, returns an array of unique values


* Array array_unique (array array)


* Inverse array element order, Preserve_key If true, array key value order is unchanged


* Array array_reverse (array Array[,boolean Preserve_key])


* Permutation array keys and values


* Array array_flip (array array)


* Array ordering, sort_flags parameter optional, default behavior


* Sort_numberic, sorted numerically, useful for sorting integers or floating-point numbers


* Sort_regular, sorted by ASCII value


* sort_string, sorted in the correct order by proximity to the person you know


* Asort function key value order unchanged


* void sort (array array[,int sort_flags])


* void Asort (array array[,int sort_flags])


* Array reverse order, sort_flags parameter optional, default behavior


* Sort_numberic, sorted numerically, useful for sorting integers or floating-point numbers


* Sort_regular, sorted by ASCII value


* sort_string, sorted in the correct order by proximity to the person you know


* Arsort function key value order unchanged


* void Rsort (array array[,int sort_flags])


* void Arsort (array array[,int sort_flags])


* Array Natural Ordering


* void Natsort (array array)


* Natural sorting without case sensitivity


* void Natcasesort (array array)


* Key values are sorted by array


* Boolean ksort (array array[,int sort_flags])


* Key values of the array of reverse order


* Boolean krsort (array array[,int sort_flags])


* Sorted by user Custom order


* void Usort (array array,callback function_name)


* Merges the arrays together to return a federated array. Array_merge behind the front, array_merge_recursive merge together


* Array Array_merge (array Array1[array array2 ...]) More than one


* Array array_merge_recursive (array Array1,array array2[,array ...]) More than two


* Keys and values form a new array


* Array Array_combine (array Key,array value)


* Returns a portion of the array, starting at offset and ending at offse+length position


* Array array_slice (array array, int offset [, int length])


* Delete all elements from offset to end of offset+length and return deleted elements as an array


* Array Array_splice (array, int offset [, int length[,array peplacement]])


* To find the intersection of the array, the key value is the first array of key values


* Array array_intersect (array Array1,array array2[,arrayn ...])


* The intersection of the array contains the same key value, the key value is the key value in the first array


* Array Array_intersect_assoc (array Array1,array array2[,arrayn ...])


* To find the difference set of the array, the first array of values in other arrays


* Array Array_diff (array Array1,array array2[,arrayn ...])


* To find the difference set of the array, the first array of values in the other array contains the same key value


* Array Array_diffassoc (array Array1,array array2[,arrayn ...])


* Returns one or more key values in an array


* Mixed Array_rand (array array[,int num_entries])


* Immediately shuffle function


* Void Shuffle (array input_array)


* Sum the values in the array


* Mixed Array_sum (array array);


* Decompose an array into a multidimensional array that contains the size element


* Array array_chunk (array array, int size [, Boolean Preserve_keys])


*/

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.