Blog de programación, errores, soluciones

Chose Language:
Author: Admin/Publisher |finished | checked

PHP array_unshift function

The PHP function array_unshift inserts one or more elements at the beginning of the array.

Description / Descripción
array_unshift(array &$array, mixed ...$values): int
Sintaxis / Sintax
$narray = array_unshift($array,$value);

Numeric arrays will be modified to start from 0.

After using this function, the internal pointer will be reset, leaving it at the first element

Parameters

$array – the array to which new elements will be added to the left.

$values – the values we will add.

Returns

int – returns the number of new elements in the array.

PHP array_unshift examples

This function is not intended for use with associative arrays, but it will still work, leaving their keys intact. However, it will add elements with indices starting from 0. We will see an example later.
utilizando array_unshift en un array asociativo
$pearson = array(
    "nombre" => "Juan",
    "edad" => 25,
    "ciudad" => "EjemploCity"
);
array_unshift($pearson,"Paraguay");

print_r($pearson);
Array
(
    [0] => Paraguay
    [nombre] => Juan
    [edad] => 25
    [ciudad] => EjemploCity
)

Numeric array example:

usando array_unshift en un array numerico
$numeros = array(10, 20, 30, 40, 50);
array_unshift($numeros,1,2);
print_r($numeros);
Array
(
    [0] => 1
    [1] => 2
    [2] => 10
    [3] => 20
    [4] => 30
    [5] => 40
    [6] => 50
)

Uses

Queue Management: If you are implementing a queue of elements and need to insert new elements at the beginning of the queue so that they are processed first, array_unshift can be useful.

$queue = array();
array_unshift($queue, "Nuevo elemento");

History or Stack Handling: In situations where you are building a history or a stack of elements and want to add new elements at the top so that they are the most recent ones.

$history = array("Elemento antiguo");
array_unshift($history, "Nuevo elemento");

Normally, you would push and pop in a stack, but you could also do something like this if there are elements you want to remove from the end.

If you are interested in the topic of stacks and queues, you can learn more about it on the following page Stacks_and_Queues – everythingcomputerscience.com
Category: en-php
Something wrong? If you found an error or mistake in the content you can contact me on Twitter | @luisg2249_luis.
Last 4 post in same category