PHP array and data stack related functions

Time:2020-2-25

The PHP array can be operated from the stack angle, which includes the following functions: array? Pop(), array? Push, array? Shift(), array? Unshift().

Array? Pop() function

Remove the last element of the array, that is, stack out;

Only one parameter of the function is the array to be operated. Here is the reference value, which will change the array to be operated;

Function to return the element from the stack.

 $arr = [1, 2, 3, 4];
 ( $arr );
 ( $arr );
 // array(3) {
 //     [0] =>
 //     int(1)
 //     [1] =>
 //     int(2)
 //     [2] =>
 //     int(3)
 //   }

Array? Push() function

The opposite operation is performed by the array? Pop function, which adds one or more elements from the end of the array, that is, the stack;

  ( array &$array , mixed $value1 [, mixed $... ] ) : int

The first parameter of the function is the target array (reference the passed value), and the next is the value to be added to the stack;

Function to return the number of stacks.

 $arr = [1, 2, 3, 4];
 ( ( $arr, 5, 6 ) );
 ( $arr );
 // int(6)
 // array(6) {
 //     [0] =>
 //     int(1)
 //     [1] =>
 //     int(2)
 //     [2] =>
 //     int(3)
 //     [3] =>
 //     int(4)
 //     [4] =>
 //     int(5)
 //     [5] =>
 //     int(6)
 //   }

Array? Shift() function

Move out the first element of the array, the number keys of the array will be counted again from zero, the non number keys will not;

There is only one parameter of the function, that is, the array of operations and the reference value.

The function returns the removed element, if not null.

 $arr = [1, 2, 3, 4];
 ( ( $arr ) );
 ( $arr );
 // int(1)
 // array(3) {
 //     [0] =>
 //     int(2)
 //     [1] =>
 //     int(3)
 //     [2] =>
 //     int(4)
 //   }

Array? Unshift() function

Insert one or more values from the beginning of the array (the order of value passing is the order of the newly inserted elements in the array);

  ( array &$array [, mixed $... ] ) : int

After inserting, the number keys of the array will be counted again from zero, and the non number keys will not;

Function returns the new length of the array after insertion.

 $arr = [1, 2, 3, 4];
 ( ( $arr, -2, -1, 0 ) );
 ( $arr );
 // int(7)
 // array(7) {
 //     [0] =>
 //     int(-2)
 //     [1] =>
 //     int(-1)
 //     [2] =>
 //     int(0)
 //     [3] =>
 //     int(1)
 //     [4] =>
 //     int(2)
 //     [5] =>
 //     int(3)
 //     [6] =>
 //     int(4)
 //   }

 

Recommended Today

Laravel service container must know

The article was forwarded from the professional laravel developer community. Original link: https://learnku.com/laravel/t To learn how to build an application with laravel is not only to learn how to use different classes and components in the framework, but also to remember allartisanCommand or all helper functions (we have Google). Learning to code with laravel is […]