Home  >  Article  >  Backend Development  >  How to add and delete array elements in php

How to add and delete array elements in php

WBOY
WBOYOriginal
2016-07-25 09:03:571021browse
  1. $fruits = array("apple","banana");
  2. array_unshift($fruits,"orange","pear")
  3. // $fruits = array("orange","pear"," apple","banana");
Copy code

Add elements at the end of the array

The return value of the

array_push() function is of type int, which is the number of elements in the array after pushing the data. You can pass multiple variables as parameters to this function and push multiple variables into the array at the same time. Its form is: (array array,mixed variable [,mixed variable...])

The following example adds two more fruits to the $fruits array:

  1. $fruits = array("apple","banana");
  2. array_push($fruits,"orange","pear")
  3. //$fruits = array("apple","banana", "orange","pear")
Copy code

Delete value from array head

array_shift() function removes and returns the element found in the array. The result is that if you are using numeric keys, all corresponding values ​​are shifted down, while arrays using associative keys are not affected. Its form is: mixed array_shift(array array)

The following example deletes the first element apple in the $fruits array:

  1. $fruits = array("apple","banana","orange","pear");
  2. $fruit = array_shift($fruits);
  3. // $fruits = array("banana", "orange","pear")
  4. // $fruit = "apple";
Copy code

Delete elements from the end of the array

array_pop() function removes and returns the last element of the array. Its form is: mixed array_pop(aray target_array);

The following example removes the last state from the $states array:

  1. $fruits = array("apple","banana","orange","pear");
  2. $fruit = array_pop($fruits);
  3. //$fruits = array("apple", "banana","orange");
  4. //$fruit = "pear";
Copy code

Remarks: PHP provides some functions for expanding and shrinking arrays. These functions provide convenience for programmers who wish to emulate various queue implementations (FIFO, LIFO). As the name suggests, the function names of these functions (push, pop, shift, and unshift) clearly reflect their functions.

The traditional queue is a data structure. The order of deleting elements and adding elements is the same, which is called first-in-first-out, or FIFO. In contrast, a stack is another data structure in which elements are removed in the reverse order in which they were added. This becomes last-in-first-out, or LIFO.



Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn