PHP entry array for use to face questions

Source: Internet
Author: User
Tags arrays explode numeric lowercase mixed prev scalar shuffle


1. The concept of arrays

An array is a named range that is used to store a series of variable values.

Each array element has an associated index (also a keyword) that can be used to access elements.

PHP allows you to use numbers or strings evenly as an index of an array.

2. Digital Index Array

2.1 Initialization of an array of numeric indices

$products = Array (' tires ', ' oil ', ' Spark plugs ');
If you need to keep numbers in ascending order in an array, you can use the range () function to automatically create the array.

Create a 1-10 array of numbers:

$numbers = range (1,10);
The optional third parameter allows the values to be set between the stride.

Create an odd array between 1-10:

$odds = range (1,10,2);
2.2 Accessing the contents of an array

By default, the 0 element is the first element of the array, using $products[0, $products [1], $products [2], you can use the contents of the array $products.

In addition to access, the contents of the array can be modified and added:

$products [3] = ' fuses ';
Like other variables in PHP, arrays do not need to be initialized or created. They are created automatically the first time they are used.

The following code creates an array that is the same as the $products array created earlier using the array () statement:

$products [0] = ' tires ';

$products [1] = ' oil ';

$products [2] = ' Spark plugs ';
The size of the array changes dynamically depending on how many elements are added.

2.3 Using iterating over arrays

is to traverse the array:

foreach ($products as $current) {

echo $current. " “;

}
The above code saves each element in the $current variable in turn and prints them.

3. Using arrays of different indexes

In the $products array above, allow PHP to specify a default index for each element. This means that the first element added is element 0, the second element is 1, and so on. PHP also supports associative arrays.

3.1 Initializing an associative array

The code shown below can create an associative array with a product name as a keyword and a price as a value:

$prices = Array (' Tires ' =>100, ' oil ' =>10, ' Spark plugs ' =>4);

3.2 Using circular statements

Because the index of the associative array is not a number, you cannot use the FOR Loop statement to operate on the array. However, you can use the Foreach Loop or the list () and each () structure.

When you use a Foreach Loop statement to manipulate an associative array, you can use the keyword as follows:

foreach ($prices as $key => $value) {

echo $key. "-". $value. " <br/> ";

}
The code shown below will print the contents of the $prices array using the each () structure.


while ($element = each ($prices)) {

echo $element [' key '];

echo "-";

echo $element [' value '];

echo "<br/>";

}

In this piece of code, the variable $element is an array. When each () is called, it returns an array with 4 values and 4 indexes pointing to the array position. The location key and 0 contain the keywords for the current element, while position value and 1 contain the values of the current element.

In addition to these two ways, function list () can be used to decompose an array into a series of values.

while (the list ($product, $price) = each ($prices)) {

echo "$product-$price <br/>";

}
This looks pretty tall. Use each () to remove the current element from the $prices array and return it as an array, then point to the next element. Also use list () to change the 0, 12 elements contained in the array returned from each () to two new variables named $product and $price.

The results of three output modes are the same:

Note that when you use the each () function, the array records the current element. If you want to use the array two times in the same script, you must reset the current element to the beginning of the array by using the function. To traverse the array again, you can use the following code:

Reset ($prices);

while (the list ($product, $price) = each ($prices))

echo "$product-$price <br/>";
The above code can reset the current element to the beginning of the array, allowing the array to be traversed again.

4. Array operators

Where the Union operator (+) attempts to add elements from the $b to the end of the $a. If the elements in $b have the same index as some elements in $a, they will not be added. That is, the elements in the $a will not be overwritten.

5. Multidimensional arrays

5.1 Two-dimensional array

$products = Array (' TIR ', ' tires ', 100),

Array (' oil ', ' oil ', 10),

Array (' SPK ', ' Spark plugs ', 4));
You can use a double for loop to access each element:


for ($row = 0; $row < 3; $row + +) {

for ($column = 0; $column < 3; $column + +) {

echo ' | '. $products [$row] [$column];

}

echo ' |<br/> ';

}

You can use column names instead of numbers. To save the same collection of products, you can use the following code:


$products = Array (' Code ' => ' TIR '),

' Description ' => ' tires ',

' Price ' =>100

),

Array (' Code ' => ' oil ',

' Description ' => ' oil ',

' Price ' =>10

),

Array (' Code ' => ' SPK ',

' Decription ' => ' Spark plugs ',

' Price ' =>4

)

);

It is much easier to use this array if you want to retrieve a single value. With a descriptive index, you do not need to remember that an element is stored in a [x][y] location. Using a pair of meaningful row and column names as an index makes it easy to find the data you need.

Traversal of descriptive indexes:


for ($row = 0; $row < 3; $row + +) {

while (list ($key, $value) =each ($products [$row])) {

echo "| $value";

}

echo ' |<br/> ';

}

5.2 Three-dimensional array

A three-dimensional array is an array of arrays containing arrays.


$categories = Array (

Array

Array (' Car_tir ', ' tires ', 100),

Array (' Car_oil ', ' oil ', 10),

Array (' CAR_SPK ', ' Spark plugs ', 4)

),

Array

Array (' Van_tir ', ' tires ', 120),

Array (' Van_oil ', ' oil ', 12),

Array (' VAN_SPK ', ' Spark plugs ', 5)

),

Array

Array (' Trk_tir ', ' tires ', 150),

Array (' Trk_oll ', ' oil ', 15),

Array (' TRK_SPK ', ' Spark plugs ', 6)

)

);

Traverse:


for ($layer = 0; $layer < 3; $layer + +) {

echo "Layer $layer <br/>";

for ($row = 0; $row < 3; $row + +) {

for ($column = 0; $column < 3; $column + +) {

echo ' | '. $categories [$layer] [$row] [$column];

}

echo ' |<br/> ';

}

}

Depending on how you create a multidimensional array, you can create four-dimensional, five-D, or six-dimensional arrays. Interested can try.

6. Array Ordering

6.1 Using the sort () function

The sort () function can sort the array in ascending alphabetical order:


$products = Array (' Lilei ', ' Hanmeimei ', ' Wo ');

Sort ($products);

foreach ($products as $key) {

echo $key. " ";

}

You can also sort by numeric order. It should be noted that the sort () function is case-sensitive. All uppercase letters precede the lowercase letters.

The second argument is optional, which specifies the sort type: sort_regular (default), Sort_numeric, or sort_string.

6.2 Sorting associative arrays using the Asort () function and the Ksort () function

If you use associative arrays to store individual items and their prices, you need to use different sort functions to keep keywords and values consistent when you sort them.

Create an array that contains 3 products and prices as follows:

$prices = Array (' Tires ' =>100, ' oil ' =>10, ' Spark plugs ' =>4);
The function asort () sorts according to each element value of the array:


Asort ($prices);

while (the list ($product, $price) = each ($prices)) {

echo "$product-$price <br/>";

}

The function Ksort () is sorted according to each of the keywords of the array:


Ksort ($prices);

while (the list ($product, $price) = each ($prices)) {

echo "$product-$price <br/>";

}

6.3 Reverse Sort

Descending sort, which corresponds to sort (), Asort (), Ksort (), respectively, Rsort (), Arsort (), Krsort ().

7. Ordering of multidimensional arrays

7.1 User-defined sort


$products = Array (

Array (' TIR ', ' tires ', 100),

Array (' oil ', ' oil ', 10),

Array (' SPK ', ' Spark plugs ', 4)

);

Custom sorting requires a function usort () to tell PHP how to compare individual elements. To do this, you need to write your own comparison functions.

The second column in the order array is sorted alphabetically as shown below:


function Compare ($x, $y) {

if ($x [1] = = $y [1]) {

return 0;

}

else if ($x [1] < $y [1]) {

return-1;

}

else{

return 1;

}

}

Usort ($products, ' compare ');

for ($row = 0; $row < 3; $row + +) {

for ($column = 0; $column < 3; $column + +) {

echo ' | '. $products [$row] [$column];

}

echo ' |<br/> ';

}

In order to be able to be used by the Usort () function, the compare () function must compare $x and $y. If $x equals $y, the function must return 0, and if $x is less than $y, the function must return a negative number, or a positive number if it is greater than. The last sentence calls the built-in function Usort (), which uses parameters such as the array ($products) and the comparison function name (compare ()) that you want to save.

If you want the array to be stored in another order, just write a different comparison function.

The "U" in Usort () represents "user" because this function requires an incoming user-defined comparison function.

7.2 Reverse User sorting

User-defined sorting does not have a reverse variant, but a multidimensional array can be sorted in reverse order. Because the user should provide a comparison function, you can write a comparison function that returns the opposite value:


function Reverse_compare ($x, $y) {

if ($x [2] = = $y [2]) {

return 0;

}

else if ($x [1] < $y [1]) {

return 1;

}

else{

return-1;

}

}

8. Reordering of arrays

Shuffle () function: Randomly sort the elements of an array.

Array_reverse () function: gives a reverse ordering of an original array.

9. Load an array from a file

Current order File:


<?php
Create short variable name
$DOCUMENT _root = $_server[' Document_root '];

$orders = File ("$DOCUMENT _root/orders.txt");

$number _of_orders = count ($orders);
if ($number _of_orders = = 0) {
echo "<p><strong>no orders pending.
Please try again later.</strong></p> ";
}

for ($i =0; $i < $number _of_orders; $i + +) {
echo $orders [$i]. " <br/> ";
}
?>

You can also load each section in an order into a separate array element so that you can process each section separately or better format them.

Separate and format the contents of the Order in PHP:


<?php
Create short variable name
$DOCUMENT _root = $_server[' Document_root '];
?>
<title>bob ' s Auto parts-customer orders</title>
<body>
<?php
Read in the entire file.
Each order becomes a element in the array
$orders = File ("$DOCUMENT _root/orders.txt");

Count the number of orders in the array
$number _of_orders = count ($orders);

if ($number _of_orders = = 0) {
echo "<p><strong>no orders pending.
Please try again later.</strong></p> ";
}

echo "<table border=\" 1\ ">\n";
echo "<tr><th bgcolor=\" #CCCCFF \ ">order date</th>
<th bgcolor=\ "#CCCCFF \" >Tires</th>
<th bgcolor=\ "#CCCCFF \" >Oil</th>
<th bgcolor=\ "#CCCCFF \" >spark plugs</th>
<th bgcolor=\ "#CCCCFF \" >Total</th>
<th bgcolor=\ "#CCCCFF \" >Address</th>
<tr> ";

for ($i =0; $i < $number _of_orders; $i + +) {
Split up/Line
$line = Explode ("t", $orders [$i]);

   //Keep only the number of items ordered
    $line [1] = Intval ($line [1]);
&nb sp;   $line [2] = Intval ($line [2]);
    $line [3] = Intval ($line [3]);

Output each order
echo "<tr>
<td> ". $line [0]." </td>
<TD align=\ "right\" > ". $line [1]." </td>
<TD align=\ "right\" > ". $line [2]." </td>
<TD align=\ "right\" > ". $line [3]." </td>
<TD align=\ "right\" > ". $line [4]." </td>
<td> ". $line [5]." </td>
</tr> ";
}

echo "</table>";
?>
</body>

Here you use the explode () function to separate each row so that you can do some processing and formatting before you start printing. In the previous article, the data was saved with a tab character as the delimiter, so it would be invoked as follows:

Explode ("T", $orders [$i]);
You can use many methods to extract numbers from a string. Here you use the Intval () function, which converts a string into an integer.

10. Perform other array operations

10.1 Browsing in the array: each (), current (), reset (), end (), Next (), POS (), and Prev ()

If you create a new array, the current pointer is initialized and points to the first element of the array.

Calling current ($array _name) returns the first element.

Calling next () or each () causes the pointer to move forward one element. The invocation of each ($array _name) returns the current element before the pointer moves one position forward. The call next ($array _name) moves the pointer forward before returning the new current element.

The Reset () function returns a pointer to the first element of the array.

The end () function returns a pointer to the last element of the array.

The Prec () function moves the current pointer back one position and then returns the new current element. You can use End () and Prev () to traverse backwards:


$array = Array (7,8,9);

$value = End ($array);

while ($value) {

echo "$value <br/>";

$value = prev ($array);

}

10.2 Apply any function to each element of the array: Array_walk ()

The Array_walk () function can use or modify each element of an array in the same way.

BOOL Array_walk (array arr,string func,[mixed UserData])
The first parameter of Array_walk () is an array that needs to be processed, and the second parameter is a function that the user customizes and will act on each element in the array.

The third parameter can be passed as a parameter to its own function, optionally.

10.3 Count the number of array elements: count (), sizeof (), and Array_count_values ()

Both the count () function and the sizeof () function can return the number of array elements.

Calling Array_count_values ($array) counts the number of occurrences of each particular value in the array $array (the base set of the array). This function returns an associative array containing the frequency table. The array includes keywords and the corresponding occurrences.

10.4 converting an array to a scalar quantity: Extract ()

The function extract () is to create a series of scalar variables by an array whose names must be the names of the keywords in the array, and the values of the variables in the array.

The extract () function has two optional parameters: Extract_type and prefix. The variable Extract_type tells the extract () How the function will handle the conflict.

The two most commonly used options are Extr_overwrite (default) and Extr_prefix_all.

$array = Array (' Key1 ' => ' value1 ', ' key2 ' => ' value2 ', ' Key3 ' => ' value3 ');

Extract ($array, Extr_prefix_all, ' my_prefix ');

echo "$my _prefix_key1 $my _prefix_key2 $my _prefix_key3";


As you may have noticed, the extract () keyword must be a valid variable name, and a keyword that starts with a number or contains a space will be skipped.

Summary of common PHP array functions


1. What is the function of converting an array's key names into lowercase and uppercase? Answer: Array_change_key_case ($array [, case_lower| Case_upper])

2. Create an array, with the value of one array as its key name, and the value of another array as its value what is the function? Answer: Array array_combine (array $keys, array $values)

3. What is the function of counting the number of values in an array? Answer: Array array_count_values (array $input)

4. What are the functions that return some or all of the key names in the array? Answer: Array Array_key ($array [, $search _value [, True|false]])

5. What is the function that functions the callback function to the cell of the given array? Answer: Array array_map (callable $callback, array $arr 1 [, Array $ ...])

6. What are the functions that combine one or more arrays? Answer: Array array_merge (array $array 1 [, Array $ ...])

7. What is the function that pops up the last element of the array? Answer: Mixed Array_pop (array & $array)

8. What is the function that presses one or more units into the end of the array (into the stack)? A: int array_push (array & $array, mixed $var [, mixed $ ...])

9. What is a function that randomly extracts one or more cells from an array? Answer: Mixed Array_rand (array $input [, int $num _req = 1])

10. What is a function that returns an array of the opposite order of cells? Answer: Array array_reverse (array $array [, bool $preserve _keys = false])

11. Search the array for a given value, and if successful, what is the function that returns the corresponding key name? Answer: Array_search (mixed $needle, array $haystack [, $strict = false])

12. What is the function that moves the cell at the beginning of the array to the group? Answer: Mixed Array_shift (array & $array)

13. What are the functions that move the duplicate values in the divisor group? Answer: Array array_unique (array $array [, int $sort _flags = sort_string])

14. What is a function that inserts one or more cells at the beginning of an array? A: int array_unshift (array & $array, mixed $var [, mixed $ ...])

15. What is the function that returns all the values in the array? Answer: Array array_values (array $input)

16. What is the function of reverse ordering of arrays and keeping an indexed relationship? A: bool Arsort (Array & $array [, int $sort _flags = sort_regular])

17. The function of a forward ordering of an array and maintaining an indexed relationship is a shot? A: bool Asort (Array & $array [, int $sort _flags = sort_regular])

18. What is the function that returns the current key/value pair in the array and moves the array pointer one step forward? A: Array each (array & $array), for example: while (List ($key, $value) =each ($array)) {}

19. What are the functions of an array in reverse order by key names? A: bool Krsort (Array & $array [, int $sort _flags = sort_regular])

20. What is the function that the array is sorted by the key name? A: bool Ksort (Array & $array [, int $sort _flags = sort_regular])

21. What is the function of the inverse ordering of the array? A: bool Rsort (Array & $array [, int = sort_regular])

22. What are the functions of the array forward ordering? A: bool sort (array [, int = sort_regular])

23. What is the function that disrupts the array? Answer: BOOL Shuffle (array)

What is the alias function for count ()? Answer: sizeof ()


Non-array, not NULL, all returns 1

<?php
$arr =array (' Spring ', ' Summer ', ' Autumn ', ' Winter ');
echo count ($arr);//4
Echo ' <br/> ';

$str = ' false ';
echo count ($str);//1
Echo ' <br/> ';

$res =null;
echo count ($res);//0
echo "<br/>";

$arr =array (' Spring ', ' Summer ', ' Autumn ', ' Winter ', Array (' A ', ' B ', ' C '));
echo Count ($arr), ' <br/> ';//5
echo Count ($arr, 1), ' <br/> ';//The 2nd argument is 1 o'clock, which represents recursion to compute the number of cells in the array.

$arr =array (' Spring ', ' Summer ', ' Autumn ', ' Winter ', Array (' A ', array (' B ', ' C '));
echo Count ($arr, 1), ' <br/> ';
?>
Range function

Function: Create an array that contains the specified range of cells

Return value: The cell from start to limit in the returned array, including themselves.

<?php
$arr =range (0,20);
foreach ($arr as $v) {
echo $v. ' <br/> ';
}
$arr =range (0,20,2);
foreach ($arr as $k => $v) {
echo $k. ' ### '. $v. ' <br/> ';
}
?>
Array_flip function Array array_flip (array $trans)

Function: Exchange key values

Parameters: Array $trans the arrays to exchange key/value pairs.

Return value: Returns the swapped array upon success if the failure returns NULL. After the key value is swapped, 2 identical keys appear, followed by the previous key

<?php
$arr =array (' A ' =>1, ' B ' =>2, ' C ' =>3);
Print_r ($arr);//array ([0] => a [1] => b [2] => c)
Print_r (Array_flip ($arr));//array ([a] => 0 [b] => 1 [c] => 2)
?>
array_sum function number Array_sum (array $array)

Function: Calculates the and of all values in an array, returning all the values in the array with the result of an integer or floating-point number.

Parameter: An array entered by array.

Return value: All values are returned with the result of an integer or floating-point number

<?php
$arr =range (1,100);
Print_r ($arr);
echo Array_sum ($arr);
?>
Shuffle function bool Shuffle (array & $array)

Function: to disrupt an array

Parameters: Array to be manipulated

Return value: Returns TRUE on success or FALSE on failure. The function is a reference pass value

<?php
$arr =range (1,100);
Print_r ($arr);
echo Array_sum ($arr);
if (Shuffle ($arr)) {
Echo ' upset success ';
Print_r ($arr);//
}
?>
Array_reverse function Array array_reverse (array $array [, bool $preserve _keys = false])

Function: To accept array arrays as input and return a new array of cells in reverse order.

Parameter: An array entered by array. Preserve_keys preserves the key of the number if set to TRUE. Non-numeric keys are not affected by this setting and are always retained.

Return value: Returns the inverted array.

<?php

$arr = Array (' A ' => ' Spring ', ' B ' => ' Summer ', ' C ' => ' Autumn ', ' d ' => ' Winter ');
Print_r ($arr); Array ([a] => spring [b] => summer [c] => autumn [d] => Winter)
Print_r (Array_reverse ($arr)); Array ([d] => winter [c] => autumn [b] => summer [a] => spring)
$arr = Array (' Spring ', ' Summer ', ' Autumn ', ' Winter ');
Print_r ($arr);
Print_r (Array_reverse ($arr));
Print_r (Array_reverse ($arr, true));
?>
array_push function int Array_push (array & $array, mixed $var [, mixed $ ...])

Action: Press one or more units into the end of the array (into the stack)

Parameter: An array entered by array. The value to which VAR is pressed.

Return value: Returns the number of elements in the array after processing.

<?php
$stack = Array ("Orange", "banana");
Array_push ($stack, "apple", "raspberry");
Print_r ($stack);
?>
Array_pop function mixed Array_pop (array & $array)

Function: Eject the last cell of the array (out of stack)

Parameters: Array needs to make a stack of arrays.

Return value: Returns the last value of an array. If the array is empty (if not an array), NULL will be returned.

<?php
$stack = Array ("Orange", "banana", "apple", "raspberry");
$fruit = Array_pop ($stack);
Print_r ($stack);
?>
Array_shift function mixed Array_shift (array & $array)

Action: Move the cell at the beginning of the array to a group

Parameter: An array entered by array.

Return value: Returns the value that is removed and returns null if the array is empty or not an array.

<?php
$stack = Array ("Orange", "banana", "apple", "raspberry");
$fruit = Array_shift ($stack);
Print_r ($stack);
?>
array_unshift function int array_unshift (array & $array, mixed $var [, mixed $ ...])

Action: Inserts one or more cells at the beginning of an array

Parameter: An array entered by array. The variable inserted at the beginning of var.

Return value: Returns the number of new cells for array arrays.

<?php
$queue = Array ("Orange", "banana");
Array_unshift ($queue, "apple", "raspberry");
Print_r ($queue);
?>

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.