Sort notes for commonly used array operations in PHP

Source: Internet
Author: User
PHP has a traditional array structure and is constantly improved with version upgrades. for example, PHP 5.4 can use short array definition syntax, which we will discuss in this article, next, let's take a look at the notes on the commonly used array operation methods in PHP: Overview
To access the content of a variable, you can directly use its name. If the variable is an array, you can use a combination of variable names and keywords or indexes to access its content.
Like other variables, you can use operator = to change the content of array elements. Array units can be accessed using the array [key] syntax.

Basic operations on arrays
Php defined array:

<?php   $array = array();   $array["key"] = "values"; ?> 

There are two ways to declare arrays in PHP:

1. use the array () function to declare an array,
2. assign values directly to array elements.

<? Php // array $ users = array ('phone ', 'computer', 'dos ', 'Linux'); echo $ users; // only the data type Array print_r ($ users) is printed ); // Array ([0] => phone [1] => computer [2] => dos [3] => linux) $ numbers = range (1, 5 ); // create an array print_r ($ numbers) that contains the specified range ); // Array ([0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5) print_r (true ); // 1 var_dump (false); // bool (false) // print_r can print the string and number simply. the Array starts with Array and is expressed as a key value, print_r outputs Boolean values and null results without significance, so it is more appropriate to use var_dump // display all values in the array through loops for ($ I = 0; $ I <5; $ I ++) {echo $ users [$ I]; echo'
';} // Count the number of units in the array or the number of attributes in the object through count/sizeof for ($ I = 0; $ I <count ($ users); $ I ++) {echo $ users [$ I]; echo'
';} // You can use the foreach loop to traverse the array. the advantage is that you do not need to consider key foreach ($ users as $ value) {echo $ value .'
'; // The point number is the string connection symbol} // foreach looping $ key => $ value; $ key and $ value are variable names, you can set foreach ($ users as $ key => $ value) {echo $ key.'
'; // Output key}?>

Create an array of custom keys

<? Php // create an array of custom keys $ ceo = array ('apple' => 'jobs', 'Microsoft '=> 'Nadella', 'Larry page ', 'Eric '); // if the key of the element is not declared, it will start from scratch print_r ($ ceo ); // Array ([apple] => jobs [microsoft] => Nadella [0] => Larry Page [1] => Eric) echo $ ceo ['apple']; // jobs // usage starting from php5.4 $ array = ["foo" => "bar", "bar" => "foo",]; print_r ($ array ); // Array ([foo] => bar [bar] => foo)?>

From php5.4, you can use the short array definition syntax and replace array () (). It is somewhat similar to the array definition in javascript.

Use of each ()

<? Php // create an array by assigning values to the array element $ ages ['trigger4'] = 22; echo $ ages .'
'; // Array // because the index of the related Array is not a number, you cannot traverse through the for loop. you can only use the foreach loop or list () and each () structure // use of each // each returns the current key/value pair in the array and moves the array pointer one step forward $ users = array ('triggerkit4' => 22, 'Mike '=> 20, 'John' => 30); // print_r (each ($ users )); // Array ([1] => 22 [value] => 22 [0] => trigkit4 [key] => trigkit4) // equivalent: $ a = array ([0] => trigkit4, [1] => 22, [value] => 22, [key] => trigkit4 ); $ a = each ($ users); // each wraps the first element of the original array into a new array and assigns it to $ a echo $ a [0]; // tri Gkit4 //!! Convert existing data to a Boolean value echo !! Each ($ users); // 1?>

The each pointer points to the first key-value pair, returns the first array element, obtains its key-value pair, and wraps it into a new array.

Use of list ()
The list is used to assign the values of the array to some variables. the following example shows the result:

<? Php $ a = ['2', 'ABC', 'Def ']; list ($ var1, $ var2) = $ a; echo $ var1 .'
'; // 2 echo $ var2; // abc $ a = ['name' => 'trigkit4', 'age' => 22, '0' => 'boys']; // list only lists the indexes whose key is a number ($ var1, $ var2) = $ a; echo $ var1; // boy?>

Note: list only recognizes the index with the key as a number.

Sorting of array elements
Reverse sorting: sort (), asort (), and ksort () are both positive sorting, and of course there is a corresponding reverse sorting.
Implementation reversely: rsort (), arsort (), and krsort ().

The array_unshift () function adds new elements to the array header. the array_push () function adds each new element to the end of the array.
Array_shift () deletes the first element in the array header. the opposite function is array_pop (). It deletes and returns an element at the end of the array.
Array_rand () returns one or more keys in the array.

The shuffle () function sorts array elements randomly.
The array_reverse () function provides a reverse sorting of the original array.
Use of APIs for arrays
Count () and sizeof () count the number of objects under the array
Array_count_values (): number of lower-level values in a group

<? Php $ numbers = array ('20140901', '2'); sort ($ numbers, SORT_STRING); // sort by string, the string is only the first size print_r ($ numbers ); // Array ([0] => 100 [1] => 2) $ arr = array ('trigkit4', 'banner ', '10'); sort ($ arr, SORT_STRING); print_r ($ arr); // Array ([0] => 10 [1] => banner [2] => trigkit4) shuffle ($ arr ); print_r ($ arr); // random sorting $ array = array ('A', 'B', 'C', 'D', '0', '1 '); array_reverse ($ array); print_r ($ array); // reverse sorting of the original array. Array ([0] => a [1] => B [2] => c [3] => d [4] => 0 [5] => 1) // Copy the array $ arr1 = array ('10', 2); $ arr2 = & $ arr1; $ arr2 [] = 4; // $ arr2 is changed, $ arr1 is still array ('10', 3) print_r ($ arr2 ); // Array ([0] => 10 [1] => 2 [2] => 4) // Use of asort $ arr3 = & $ arr1; // currently, arr1 and arr3 are the same $ arr3 [] = '3'; asort ($ arr3); // sorts the array and retains the original relationship print_r ($ arr3 ); // Array ([1] => 2 [2] => 3 [0] => 10) // Use of ksort $ fruits = array ('C '=> 'Bana', 'a' => 'apple', 'D' => 'Orange'); ksort ($ fruits); print_r ($ fruits ); // Array ([a] => apple [c] => banana [d] => orange) // use array_unshift for unshift ($ array, 'z '); // add an element print_r ($ array) at the beginning ); // Array ([0] => z [1] => a [2] => B [3] => c [4] => d [5] => 0 [6] => 1) // use echo current ($ array) for current (pos); // z; obtain the current unit in the current array // use echo next ($ array) for next ); // a; move the internal pointer in the array one forward. // use echo reset ($ array ); // Z; point the internal pointer of the array to the first unit // use echo next ($ array) for prev; // a; echo prev ($ array ); // z; returns the echo sizeof ($ array); // 7; counts the number of array elements // array_count_values $ num = array (10, 20, 30, 10, 20, 1,); // counts the number of occurrences of the array element print_r (array_count_values ($ num )); // Array ([10] => 3 [20] => 2 [30] => 1 [1] => 1 [0] => 1)?>

Current (): each array has an internal pointer pointing to its current unit, initially pointing to the first element inserted into the array

For loop traversal

<?php  $value = range(0,120,10);  for($i=0;$i
 

Array instance
Use of the array_pad function

<? Php // array_pad function, which can be appended at the beginning and end of an array $ num = array (1 => 10, 2 => 20, 3 => 30); $ num = array_pad ($ num ); print_r ($ num); // Array ([0] => 10 [1] => 20 [2] => 30 [3] => 40) $ num = array_pad ($ num,-5, 50); // array_pad (array, size, value) print_r ($ num ); // Array ([0] => 50 [1] => 10 [2] => 20 [3] => 30 [4] => 40)?>

Size: the specified length. An integer is filled to the right, and a negative number is filled to the left.

Use of unset ()

<? Php // unset () use $ num = array_fill (, rand (); // rand (min, max) print_r ($ num ); // Array ([0] => 8 [1] => 8 [2] => 8 [3] => 8 [4] => 8) echo'
'; Unset ($ num [3]); print_r ($ num ); // Array ([0] => 8 [1] => 8 [2] => 8 [4] => 8)?>

Use of array_fill ()

<? Php // Use of array_fill () $ num = range ('A', 'E'); $ arrayFilled = array_fill (, $ num); // array_fill (start, number, value) echo'
';  print_r($arrayFilled);?>

Use of array_combine ()

<?PHP  $number = array(1,2,3,4,5);  $array = array("I","Am","A","PHP","er");  $newArray = array_combine($number,$array);  print_r($newArray);//Array ( [1] => I [2] => Am [3] => A [4] => PHP [5] => er ) ?> 

Array_splice () deletes an array member.

<? Php $ color = array ("red", "green", "blue", "yellow"); count ($ color); // Get 4 array_splice ($ color, 1, 1); // delete the second element print_r (count ($ color); // 3 echo $ color [2]; // yellow echo $ color [1]; // blue?>

Array_unique: delete duplicate values in the array

<?php  $color=array("red", "green", "blue", "yellow","blue","green");  $result = array_unique($color);  print_r($result);//Array ( [0] => red [1] => green [2] => blue [3] => yellow ) ?> 

Array_flip () swap the key value and value of the array

<?PHP  $array = array("red","blue","red","Black");  print_r($array);  echo "
"; $array = array_flip($array);// print_r($array);//Array ( [red] => 2 [blue] => 1 [Black] => 3 ) ?>

Array_search ()

  <? Php $ array = array ("red", "blue", "red", "Black"); $ result = array_search ("red", $ array) // array_search (value, array, strict) if ($ result = NULL) {echo "no value red";} else {echo "value $ result "; // the value 0}?>

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.