Insertar y extraer elementos de un array‏ con PHP

En PHP para insertar o extraer elementos a un array lo podemos hacer de varias formas. En este artículo vamos a explicar como funcionan las funciones que nos facilita la librería: array_push() y array_pop().

La función array_push() inserta uno o más elementos al final de un array. Su estructura es la siguiente:

int array_push ( array &$array , mixed $var [, mixed $... ] )

La variable $array es el vector de entrada y $var el valor a insertar.

Array_push() trata array  como si fuera una pila y empuja la variable que se le pasa al final del array. El tamaño del array será incrementado por el número de variables insertados.

Si se utiliza array_push() para añadir un solo elemento en el array, es mejor utilizar $array[] = ya que de esta forma no existe la sobrecarga de llamar a una función.

La función devuelve el nuevo número de elementos en un array.

La función array_pop() extrae el último elemento del final del array. Su estructura es la siguiente:

array_pop ( array &$array )

array_pop() extrae y devuelve el último valor del array, acortando el array con un elemento menos. Si el array está vacío (o no es un array), se devolverá NULL. Además se producirá un Warning cuando se llame a un elemento que no es un array.

La función devuelve el último valor del array. Si el array está vacío (o no es un array), se devolverá NULL.

Vamos a ver un ejemplo de aplicación:

<?php
//Array inicial
$data = array("Lunes", "Martes", "Miércoles", "Jueves");
//Añadimos los valores Viernes y Sábado al array
array_push($data, "Viernes", "Sábado");
//Eliminamos el último elemento del array
$last_element = array_pop($data);
?>

Ver el ejemplo en funcionamiento

Autor
Escrito por Jose Aguilar - Director ejecutivo y tecnológico en JA Modules. Experto programador PrestaShop y Experto programador WordPress.
Te ha servido? Valora esta entrada!
(6 votos, promedio: 4 de 5)
Comparte en las redes sociales
¿Buscas trabajo de programador?

10 respuestas a “Insertar y extraer elementos de un array‏ con PHP”

  1. Bryan dice:

    Muchas gracias por compartir tus conocimientos

  2. Links…

    […]Sites of interest we have a link to[…]……

  3. four micro onde dice:

    Enjoyed studying this, very good stuff, regards .

  4. seriale torrent dice:

    First off I want to say great blog! I had a quick question in which I’d like to ask if you don’t mind. I was interested to know how you center yourself and clear your mind prior to writing. I have had a difficult time clearing my thoughts in getting my thoughts out there. I do enjoy writing however it just seems like the first 10 to 15 minutes are generally lost just trying to figure out how to begin. Any recommendations or hints? Kudos!

  5. high PR links dice:

    Yay google is my queen assisted me to find this outstanding internet site ! . «A tough lesson in life that one has to learn is that not everybody wishes you well.» by Dan Rather.

  6. 38dd swimwear dice:

    This is my first time visit at here and i am in fact pleassant to read everthing at single place.

  7. Actually no matter if someone doesn’t understand afterward its up to other users that they will help, so here it takes place.

  8. agen bola dice:

    Keep up the superb piece of work, I read few posts on this internet site and I think that your website is rattling interesting and holds circles of wonderful info .

  9. Taryn Gullotta dice:

    That is very fascinating, You are a very skilled blogger. I have joined your rss feed and sit up for in search of more of your magnificent post. Additionally, I’ve shared your web site in my social networks!

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Este sitio usa Akismet para reducir el spam. Aprende cómo se procesan los datos de tus comentarios.

Ver más sobre