Initialization of an array of PHP arrays array operator multidimensional array reordering array reordering arrays of methods from a file load a list of other useful operations statistics array converts the array to scalar variable extract () ____php

Source: Internet
Author: User
Tags scalar shuffle

1. Initialization of arrays
(1) Create an array with array
A: $products = array (' tires ', ' oil ', ' Spark plugs ');
Array () is actually a language structure, not a function

B: Initializing the related array
$prices = Array (' Tires ' =>100, ' oil ' =>10, ' Spark plugs ' =>4); To create an array with 3 elements

$prices = Array (' tires ' =>100); This is not a way to create an array with 3 elements,
$prices [' oil '] = 10; Instead, you create an array of only one element, and then add another two elements
$prices [' Spark Plus '] = 4;

$prices [' tires '] = 100; Array is created when the first element is added to the array.
$prices [' oil '] = 10; is to create an empty array first and then put the value in
$prices [' Spark Plus '] = 4;

(2) Create an array with range

If you need to save ascending numbers in an array, you can use the range () function to create the array automatically
Range (first,second,step)//step Optional. Specify the steps between elements. The default is 1.
$number = range (1,10); Create an array of numbers from 1 to 10
$odds = range (1,10,2); Create an odd array of 1 to 10
$letters = Range (' A ', ' Z ');

(3) Create an array directly
$products [0] = "tires";
$products [1] = "oil";
$products [2] = "Spark plugs";
Note the order in which the segment creates the array:
If $products does not exist, the first line of code creates an array of only one element,
The subsequent code adds a new value to the array.


2. Accessing arrays
(1) Of course the value of the array is the most convenient is foreach, this is not to say more
Notice that the index of the array starts at 0.

(2) There is a second method, with while and each ()
while ($element = each ($prices)) {
echo $element [' key '];
Echo '-';
echo $element [' value '];
echo ' <br/> ';
}

Each () returns the current element and the next element as the current element
The each () function generates an array of key names and key values of the elements that the array's current internal pointer points to, and moves the internal pointer forward.
The four elements included in the returned array: The key name is 0,1,key and value. The unit 0 and key contain the key names of the array cells, and 1 and value contain the data.
If the internal pointer crosses the array range, this function returns FALSE.

(3) List and each traversal array
while (the list ($product, $price) = each ($prices))
echo "$product-$price <br/>";

If you use the array two times in the same script, you must use Reset () to reset the current element to the beginning of the array
Reset ($prices);
while (the list ($product, $price) = each ($prices))
echo "$product-$price <br/>";

3. Array operators
---------------------------------------------------------------------------------------
Operator name Use method result
---------------------------------------------------------------------------------------
+ Union $a + $b $a and $b, the array $b will be appended to the $a,
But any element that is accented by the keyword will not be added
= = = Equivalent $a = = $b returns True if $a and $b have the same element
= = = Identity $a = = = $b both have the same element with the same order, returns true
!= non-equivalence $a!= $b returns True if $a and $b are not equivalent
<> non-equivalence $a <> $b returns True if $a and $b are not equivalent
!== non-identity $a!== $b returns True if $a and $b are not identical
---------------------------------------------------------------------------------------

+ Performs an addition operation on a scalar type, and a union array performs an addition operation

Scalar:
A scalar represents the actual memory location where the data item is stored: A string or a number. is the most basic unit of data items stored in PHP
In simple terms, variables are strings and numbers

4. Array Ordering
Sort the value of a given array in ascending order using the sort () function
The sort () function is case-sensitive, with all uppercase letters in front of the lowercase letters,
The second parameter, optional, has sort_regular,sort_numeric or sort_string, specifies the function of the sort type,
To compare strings containing numbers 2 and 12, from a number angle, 2 is less than 12, and as a string, ' 12 ' is less than ' 2 '

Asort () sorted by array element values
Ksort () sorted by array key

Sort () direction ordering Rsort ()
Asort () ==>arsort ()
Ksort () ==>krsort ()

Asort (Array,sorttype)
Ksort (Array,sorttype)

5. Ordering of multidimensional arrays
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 ');

Sort () ==>usort ()
Asort () ==>uasort ()
Ksort () ==>uksort ()

But user-defined sorting does not have a reverse variant
But you can write reverse sort functions
function Reverse_compare ($x, $y) {

if ($x [1] = = $y [1])
return 0;
else if ($x [1] < $y [1])
return 1;
Else
return-1;

}

Usort ($products, ' reverse_compare ');

Usort (Array,sorttype)
Array required. Specify the array to sort.
function Required. User-defined functions.

The function must be designed to return-1, 0, or 1, and should accept two parameters for comparison, and work in a manner similar to the following:

If a = B, return 0
If a > B, return 1
If a < B, returns the return value specified in 1 0,1,-1

6. Reordering of arrays
(1) Shuffle () reorder the arrays
This function assigns a new key name to the cell in the array. This deletes the original key name and not just the reordering.


<?php
$my _array = Array ("A" => "Dog", "B" => "Cat", "C" => "horse");
Shuffle ($my _array);
Print_r ($my _array);
?> output:

Array ([0] => Cat [1] => horse [2] => Dog)//The original A,b,c key name is deleted and the new key name is 0,1,2


(2) the Array_rand (array,number) function randomly selects one or more elements from an array and returns.
If more than one element is selected, the array containing the random key name is returned, otherwise the key name of the element is returned.
Returns the key name, not the value

Such as:
<?php
$a =array ("a" => "Dog", "B" => "Cat", "C" => "horse");
Print_r (Array_rand ($a, 2));
?>

Output:

Array ([0] => C [1] => B)

(3) Array_reverse (Array,preserve)
Returns an array whose contents are the same as the parameter array but in the opposite order, creating a new array and returning it.
If the second argument is specified as true, the key name of the element remains unchanged or the key is lost.

(4) If the array is a series of integers, you can use the range () function
$number = Range (10,1,-1)//Create an array in the opposite order

Summary: (1) array_reverse (), shuffle () are all to create a new array,
Array_rand does not need to create a new array.

(2) Array_rand returns the key array group,
Shuffle () The original key name is replaced by the new key name,
Array_recerse () can set whether the original key name is preserved


7. How to load an array from a file

When the login information is placed in the file, the login verification uses file to remove the files into the array and then process them instead of a single processing

$file _array = File ("$DOCUMENT _root//test//content.txt");
foreach ($file _array as $key => $value) {
$value _array = explode ("|", $value);
foreach ($value _array as $value _key=> $value _value) {
echo $value _value. " <br> ";
}
}

8. Other useful operations of the array
Each () returns the current pointer element, moving the pointer forward one position until the end of the array.
Next () Moves the pointer forward one element, as with each, but next () moves the pointer forward and then returns the new current element.
Each () returns the current element before the pointer moves one position forward
(Why does the pointer move forward, because the array is as advanced as the stack, so the next element of the current element is on top of the current element)
Prev () Moves the current pointer back one position and then returns the new current element, as opposed to next ()

Current () returns the first element (that is, when you return the creation of a new array, the present pointer is initialized, and the current pointer is the first element)

Reset () Returns a pointer to the first element of the array
End () Moves the pointer to the ends of the array

The difference between current () and reset ()
The current () function returns the value of the array element that is currently pointed to by the internal pointer, and does not move the pointer. is the first element that returns the initialization of an array without affecting the function that uses the pointer
Reset () will move the pointer to the first element of the array, and then affect the function that uses the pointer

The values returned by the above function are all element values.


9. Array_walk ()

Definitions and usage
The Array_walk () function applies a callback function to each element in the array. Returns TRUE if successful, otherwise returns FALSE.

Typically, a function accepts two parameters. The value of the array parameter is the first, and the key name is the second. If an optional parameter userdata is provided, it is passed as the third argument to the callback function.

If a function function requires more arguments than is given, a e_warning error is generated each time Array_walk () invokes the function. These warnings can be suppressed by adding PHP's error operator @ before the Array_walk () call, or by using error_reporting ().

Grammar
Array_walk (Array,function,userdata ...) Parameter description
Array required. The specified array.
function Required. The name of the user-defined function.
UserData Optional. The value entered by the user as a parameter to the callback function.
Tips and comments
Tip: You can set one or more parameters for a function.

Note: If the callback function needs to act directly on the value in the array, you can specify the first argument of the callback function as the reference:& $value. (see example 3)

Note: Passing the key name and UserData to the function is a new addition to PHP 4.0.
Example 1
<?php
function MyFunction ($value, $key)
{
echo "The key $key has the value $value <br/>";
}
$a =array ("a" => "Cat", "B" => "Dog", "C" => "horse");
Array_walk ($a, "myfunction");
?> output:

The key A has the value Cat
The key B has the value Dog
The key C has the value horse Example 2
With one parameter:

<?php
function MyFunction ($value, $key, $p)
{
echo "$key $p $value <br/>";
}
$a =array ("a" => "Cat", "B" => "Dog", "C" => "horse");
Array_walk ($a, "myfunction", "has the value");
?> output:

A has the value Cat
B has the value Dog
C has the value horse Example 3
Change the value of an array element (Note & $value):

<?php
Function MyFunction (& $value, $key)
{
$value = "Bird;
}
$a =array ("a" => "Cat", "B" => "Dog", "C" => "horse");
Array_walk ($a, "myfunction");
Print_r ($a);
?> output:

Array ([a] => Bird [b] => Bird [c] => Bird)


10. Count the number of arrays
Count (Array,mode)

mode is optional. The pattern of the specified function. Possible values:

0-Default. does not detect multidimensional arrays (arrays in an array).
1-detects multidimensional arrays. (or count_recursive)
Note: This parameter is added in PHP 4.2.
sizeof () is an alias for Count

Array_count_value () counts the number of occurrences of all values in the array
Returns an array whose key name is the value of the original array, and the key value is the number of times the value appears in the original array
<?php
$a =array ("Cat", "Dog", "Horse", "Dog");
Print_r (Array_count_values ($a));
?> output:

Array ([Cat] => 1 [Dog] => 2 [horse] => 1)

  $array =array (4,5,1,2,3,1,2,1);
  $AC =array_count_value ($array);
  will create an array named $ac, which includes:
        
           key       Value
         4          1
         5          1
        1           3
        2           2
        3           1


11. Convert an array to a scalar variable extract ()
Extract (Array,extract_rules,prefix)
The second parameter type specifies how the extract () function treats such a conflict when a variable already exists and an element with the same name is in the array.

3 more commonly used types
Extr_overwrite-Default. If there is a conflict, overwrite the existing variable.
Extr_prefix_same-If there is a conflict, precede the variable name with the prefix PREFIX. Since PHP 4.0.5, this also includes processing of digital indexes.
Extr_prefix_all-Prefix all variable names PREFIX (third argument).

$ = "Original";
$my _array = Array ("A" =>cat, "B" => "Dog", "C" => "horse");
Extract ($my _array);
echo "/$a = $a; /$b = $b; /$c = $c ";

Results:
$a = Cat; $b = Dog; $c = Horse

If the same variable existed before

<?php
$a = ' Original ';
$my _array = Array ("A" => "Cat", "B" => "Dog", "C" => "horse");

Extract ($my _array,extr_prefix_same, ' dup ');

echo "/$a = $a; /$b = $b; /$c = $c; /$dup _a = $dup _a; ";
?> output:

$a = Original; $b = Dog; $c = horse; $dup _a = Cat;

Note: Extract () can extract an element with a keyword that must be a valid variable name
That is, a keyword that starts with a number or contains a space will be skipped without putting a variable in it.

Related Article

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.