Your location:Tech News>News>Script>[Detailed PHP array traversal operation, pointers, function, etc.]

Latest News

[Detailed PHP array traversal operation, pointers, function, etc.]



  This paper summarizes the example PHP array operations.Share to you for your reference, as follows:


  Of data elements, the elements of the key and a value

  Array Category

  Associative array

  Associative array, the subscript value of Elements element logical relationship exists, known as an associative array.It refers to the presence management between the key and values.

  $ A1 = array ( ''name'' => ''Xunhuan'', ''age'' => 34);

  Indexed array

  Indexed array, and the subscript value absence of logic elements, and the subscript value represents the index position only.

  $ A1 = array ( ''Xunhuan'', 34);

  Array traversal

  To traverse the array to complete the required order to obtain the information (value information and the key information) of each element.The core elements of the array of pointers that

  Elements of an array of pointers

  Each pointer points, has an internal element in an array.

  By default, this pointer points to the first element of the array.

  Each array is only a pointer, at the same time time, only point to one element, and therefore the position of the pointer, may be any element of an existing.While external array pointer may point to (the end of the array [outside the last one]), the position is illegal.


  Array traversal is

  Obtaining information element pointer, move the pointer, with the loop structure can be completed.

  php offer

  Get pointer points to information elements

  Move the cursor

  Current (); get pointer to the value of the current element

  Key (); to give currently pointing key element

  Next (); you can move the pointer array

  PREV (); Move one element.

  RESET (); Pointer reset (to move the first element)

  End (); moved to a rightmost element

  End of the array, a rightmost element right, illegal range

  next (), and PREV (); array pointer may be moved to a position on illicit.

  // $ students is an array

  end ($ students);

  next ($ students);

  var_dump (current ($ students)); // false;

  reset ($ students);

  prev ($ students);

  var_dump (current ($ students)); // false;

  If the position has moved to the illicit, to restore the relative movement is not, at this time, a mandatory move to a position, RESET (), and end ()

  // $ students is an array

  end ($ students);

  next ($ students);

  prev ($ students);

  var_dump (current ($ students)); // false;

  reset ($ students);

  prev ($ students);

  next ($ students);

  var_dump (current ($ students)); // false;

  foreach ()

  the foreach (); Structure

  A dedicated array traversal of the structure, a loop structure is

  foreach ($ arr as $ key => $ val) {

  // loop


  If the key elements does not make sense, you can use the information omitted key

  foreach ($ arr as $ val) {}


  foreach array pointer will move, and, after completion foreach traversal, the pointer is illegal position (end of the array)

  foreach when traversing an array element, the element will initialize the pointer, the position pointer is thus, will not affect the traversal foreach

  foreach is traversed, a copy of the original array, rather than directly in the original array traversal, if during traversal, the traversal of the array to be modified, will not affect the traversal results

  Foreach variable holds the element value is used, its operation, does not affect the original array

  The operation of the value, while supporting passed by reference: You can change the value of the original array.

  Just add an ampersand to the variable before.


  foreach flow chart


  foreach loop structure is, by controlling the break and continue.

  each ()

  Through each

  You can obtain current information element.(Keys and values), while moving the pointer down

  Obtain information element, returns, and related indexed array

  among them:

  Associative array section.

  Key key => the current element

  value => element value

  Partially indexed array

  0 => subscript element

  1 => element

  $ Arr = array (10, 12, 200);

  $ Arr2 = array (

  ''Name'' => ''zf'',

  ''Age'' => 20


  var_dump (each ($ arr));

  var_dump (each ($ arr2));

  Traversing the first term

  Since each element information may be acquired, and you can move the pointer, so it is suitable to complete through the array of manually except foreach.

  Iterate each + while + list of

  If each pointer illegal, each returns false. Analyzing each return value

  // first eaech, the result is assigned to each of the $ element

  // $ element to determine whether to set up (automatically converted into Boolean type)

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

  echo ''Key:'', $ element [0];

  echo ''$ nbsp;'';

  echo ''Value:'', $ element [1];

  echo ''


  list ()

  Can use the underlying variable element is directly stored in the loop body traversed.Variables used directly underlying variable elements under preservation and conservation element values.

  A function that can be an array, for a plurality of simultaneous variable initialization

  $ Student = array ( ''Xunhuan'', ''secret for the elderly'', ''punk'');

  list ($ a, $ b, $ c) = $ student; // the elements within the array, in order to assign the variables // list structure in similar destructuring assignment es6

  var_dump ($ a, $ b, $ c);

  list to take effect for indexed array

  $ Student = array ( ''Xunhuan'', ''secret for the elderly'', ''punk'');

  while (list ($ k, $ v) = each ($ student)) {

  echo ''Key:'', $ k;

  echo '''';

  echo ''Value:'', $ v;

  echo ''


  Copies the array element pointer

  If the original array pointer legitimate:

  When you copy an array, the pointer position is also copied to the target array.

  $ A1 = array ( ''a'', ''b'', ''c'');

  $ A2 = $ a1;

  var_dump (current ($ a2)); // a

  echo ''


  $ A1 = array ( ''a'', ''b'', ''c'');

  next ($ a1);

  $ A2 = $ a1;

  var_dump (current ($ a2)); // b

  If the original array pointer illegal:

  Reset the pointer to the new array; reset to the default pointer.

  $ A1 = array ( ''a'', ''b'', ''c'');

  end ($ a1);

  next ($ a1);

  $ A2 = $ a1;

  var_dump (current ($ a2)); // a

  foreach array pointers relations

  Effect on foreach pointer uncertainty, so do not rely on the hand position foreach traversal, if necessary operations, first need to reset (RESET ();).

  Array traversal is a copy of the original array, instead of operating directly on the array.

  Php internal optimization, copy-on-write (COW - copy on write) .Without the original array write operation is performed. Copying process is not going to happen. When the original array write operation, the copying process will occur.

  Pointer array replication problem


  foreach traversal time, a copy, but occurs after the operation of the original array.Means that, before writing, direct traversal operation is the original array. Once the write operation takes place, it will form a true copy, foreach to traverse the array is not the same as the original array. Therefore, the original array pointer will not continue to change. The only exception in the last cycle of the array write vivo, in this case before the pointer has illegally copied, the result will be reset.

  In practice, it is recommended after processing, can be immediately reset ();

  The above problem, apply only to $ value, variable holds the value of the elements of the case is passed by value, if it is passed by reference words.Direct manipulation of the original array!

  $ Key can not be passed by reference.

  array function

  Common Functions

  array_fill (starting position, length, content); // fill a certain number of elements of fixed value.

  // count the number of array elements; () count. Statistical support for recursion.

  range (starting range, the end of the range); // create array elements according to the range.

  array_merge (); // concat.

  // Note that a situation of conflict index, if the index subscript conflict, in increasing order.

  // associative array conflict. After the merger to be covered by the previous.

  array_merge (range ( ''a'', ''z''), range ( ''A'', ''Z''));

  array_rand (array select number [a default]); // to make some random element from an array. The resulting index is random, and not the element values. And, if a plurality of elements, are sorted by the size of the subject.

  shuffe (); // disrupt the order of the elements, parameters are passed by reference.

  // 4 nonce verification codes

  // Create an array of mixed sizes

  $ Chars = array_merge (range ( ''a'', ''z''), range ( ''A'', ''Z''));

  // get four elements subscript

  $ Rand_keys = array_rand ($ chars, 4);

  // upset

  shuffle ($ rand_keys);

  // get the element values using the subscript

  foreach ($ rand_keys as $ v) {

  echo $ chars [$ v];


  Key operation

  array_value (); // get all the values of all the elements.

  array_key (); // get all the keys of all the elements.

  array_combine (); // use two arrays, one of which is a bond, and the other is worth to a new array.

  the in_array (); // if there is a value determined array

  array_key_exists (); // there is an element.

  array_search (); // Find the value of an element in the array, find the return index. Can not find returns false.

  array_filp (); // key and value exchange element.

  Merge Split

  ''+'' Sign

  $ A1 = array (1, 2, 3, 4);

  $ A2 = array (6, 7, 8);

  var_dump ($ a1 + $ a2); // if the index is a conflict, the elements behind ignored

  array_merge ($ arr1, $ arr2); // concat.

  array_chunk ($ arr, len); // according to the length of the subarray, a resolution of the original array.

  explode (); // a string, in accordance with a character, into a plurality of portions.

  implode (); // array element may be, the use of a character, connected

  $ Arr = array ( ''aa'', ''bb'');

  echo $ arr = implode ( ''-'', $ arr); // aa-bb

  print_r (explode ( ''-'', $ arr));

  Compact (); combined use of a plurality of variables are combined into an array. Where the variable name as the array index. Value of the variable, as the value. Note that the argument is a variable name

  $ Width = 2;

  $ Height = 10;

  $ Arr = compact ( ''width'', ''height'');

  extact (); split, a variable, split into a variable.Each element is a variable. Subscript variable name, the value of the variable value. Subscript strings.

  Note that if the current variable name already exists, replace the existing value of the variable operation occurs.This is the default behavior.Can be modified by extact (), the second parameter. The default is EXTR_OVERWRITE expressed rewrite // EXTR_SKIP expressed skip.


  array_diff (arrays 1, 2 arrays); // get the array 1 and array 2 is not in the same element. - Set difference value determination.

  array_intersect (arrays 1, 2 arrays); // get the same elements in the array 1 and array 2 in. - intersection.

  array_map ($ callback, $ arr1); // for each element in the array, once the operation.We were once call a function call.

  If the function is a custom.

  Note that, there should be a parameter receiving element values, and should return a value

  $ A1 = array (10, 20, 3);

  function x2 ($ item) {

  return $ item * 3;


  $ Arr = array_map ( ''x2'', $ a1);

  var_dump ($ arr);

  Only responsible for the definition, is not responsible for call. array_map (); function is responsible for internal calls.

  You may receive or process simultaneously.Is a unified operation, once all of the same array position are operating again, rather than one by one operation. Thus the number of parameters received by the function, the number of the passed array should be consistent.

  There is a default action, is very commonly used by a plurality of arrays, are combined into a new array.Requirements, a null position transfer function.

  $ Names = array ( ''z1'', ''z2'', ''z3'');

  $ Maths = array (50, 40, 60);

  $ Score = array_map (null, $ names, $ maths);

  var_dump ($ score);

  The callback function - analog data structure function - ranking function

  array_walk ($ funcname);

  Operation for each element of an array, the differences from the array_map.

  array_map () can operate a plurality of arrays, and array_walk (); can only operate an array.

  array_map (); only element values can be obtained, while array_walk (); i.e. element values can be obtained, the key element may also be obtained.

  Object is passed a reference to the function of the first parameter, to change the array of the original.

  $ Names = array ( ''aa'', ''bb'', ''cc'');

  function fn1 (& $ val, $ key) {

  var_dump ($ val, $ key);


  array_walk ($ names, ''fn1'');

  Analog data structure

  The array_push stack ();

  Array_pop the stack ();

  // After each operation, the index will be re-index.

  The top: array_shift ();

  The top: array_unshift ();

  Sort function

  Soft (); ascending order according to the value

  RSoft () in descending order according to the value

  ksoft () ascending key order

  krsoft (); descending according to key

  // sort value, does not retain key relationship, and sort key will remain key relationship.

  // ordered by values, while preserving the key relationship.

  asort (); according to the value, in ascending order, to retain the associated key.

  arsort (); according to the value, in descending order, to retain the associated key.

  key, key

  reverse (): reverse order, the default is ascending.

  association: association

  More about PHP-related content and interested readers can view the site topic: "PHP array (Array) operating skills Daquan", "PHP traversal algorithms and techniques commonly used summary", "php string (string) Usage summary", "php commonly used functions and skills summary "," PHP error and exception handling methods "," PHP basic syntax Start tutorial "," php Object-oriented programming Guide "and" PHP math skills summary "

  In this paper, we hope that the PHP programming help.

  You may also be interested in the article: PHP array of knowledge and basic usage summary php array pointer function and usage examples PHP function lookup method php array functions array_push an ordered array contains a certain value (), array_pop () and array_shift () Simple usage example PHP string array processing function usage summary PHP achieve two-dimensional array (or multi-dimensional array) is converted into one-dimensional array of common methods summarized PHP implemented method of extracting a multidimensional array specified php quick summary of two-dimensional array of a column assembly Summary of the operation example of a method PHP array analysis object Json how conversion array in PHP

Recommend article

Relate article