Delete array element with value php

array_pop

array_pop() извлекает и возвращает значение последнего элемента массива array , уменьшая размер array на один элемент.

Замечание: Эта функция при вызове сбрасывает указатель массива, переданного параметром.

Список параметров

Массив, из которого берётся значение.

Возвращаемые значения

Возвращает значение последнего элемента массива array . Если array пуст, будет возвращён null .

Примеры

Пример #1 Пример использования array_pop()

$stack = array( «orange» , «banana» , «apple» , «raspberry» );
$fruit = array_pop ( $stack );
print_r ( $stack );
?>

После этого в $stack будет только 3 элемента:

Array ( [0] => orange [1] => banana [2] => apple )

и raspberry будет присвоено переменной $fruit .

Смотрите также

  • array_push() — Добавляет один или несколько элементов в конец массива
  • array_shift() — Извлекает первый элемент массива
  • array_unshift() — Добавляет один или несколько элементов в начало массива

User Contributed Notes 11 notes

Notice:
the complexity of array_pop() is O(1).
the complexity of array_shift() is O(n).
array_shift() requires a re-index process on the array, so it has to run over all the elements and index them.

Note that array_pop doesn’t issue ANY warning or error if the array is already empty when you try to pop something from it. This is bizarre! And it will cause cascades of errors that are hard to resolve without knowing the real cause.

Rather than an error, it silently returns a NULL object, it appears, so in my case I ended up with warnings elsewhere about accessing elements of arrays with invalid indexes, as I was expecting to have popped an array. This behaviour (and the lack of any warning, when many trivial things are complained about verbosely) is NOT noted in the manual above. Popping an already empty stack should definitely trigger some sort of notice, to help debugging.

Sure, it’s probably good practice to wrap the pop in an if (count($array)) but that should be suggested in the manual, if there’s no error returned for trying something that should fail and obviously isn’t expected to return a meaningful result.

I wrote a simple function to perform an intersect on multiple (unlimited) arrays.

Pass an array containing all the arrays you want to compare, along with what key to match by.

function multipleArrayIntersect ( $arrayOfArrays , $matchKey )
<
$compareArray = array_pop ( $arrayOfArrays );

foreach( $compareArray AS $key => $valueArray ) <
foreach( $arrayOfArrays AS $subArray => $contents ) <
if (! in_array ( $compareArray [ $key ][ $matchKey ], $contents )) <
unset( $compareArray [ $key ]);
>
>
>

In a previous example .
function array_trim ( $array , $index ) if ( is_array ( $array ) ) unset ( $array [ $index ] );
array_unshift ( $array , array_shift ( $array ) );
return $array ;
>
else return false ;
>
>
?>

This have a problem. if u unset the last value and then use
array_unshift ( $array, array_shift ( $array ) );
?>

will return a : Array ( [0] => )
so u can fix it using.

if ( count ( $array ) > 0 ) array_unshift ( $values , array_shift ( $values ) );
?>

good luck 😉

alex.chacon@terra.com
Hi
Here there is a function that delete a elemente from a array and re calculate indexes

function eliminarElementoArreglo ( $array , $indice )
<
if ( array_key_exists ( $indice , $array ))
<
$temp = $array [ 0 ];
$array [ 0 ] = $array [ $indice ];
$array [ $indice ] = $temp ;
array_shift ( $array );

//reacomodamos ?ndices
for ( $i = 0 ; $i < $indice ; $i ++)
<
$dummy = $array [ $i ];
$array [ $i ] = $temp ;
$temp = $dummy ;
>
>
return $array ;
>
?>

I had a problem when using this function because my array was made up entirley of numbers, so I have made my own function. Hopefully it will be useful to somebody.

Источник

How to Delete or Remove Array Element By Value in PHP

In this tutorial, learn how to delete or remove array element by value using PHP. The short answer is to use the unset() function of PHP that takes array variable with key as an argument.

You can also use the array_splice() method to remove the specified element from an array in PHP. Let’s find out different methods with examples given below here.

Method 1: Using unset() to Remove Array Element By Value in PHP

To remove the given element from an array by value, you have to first find the index of the element or the key. You can identify the index or key of the element using the array_search() as given below. After that, you have to use the unset() function to remove the specified element from an array.

Array ( [0] => Cycle [2] => Car [3] => Bolero )

The above example shows the output that is an array with the element “Bike” remove from it. The resulted array is not in the proper sequence of indexing. You can use the next method to make the array in proper sequence.

Method 2: Using array_splice() to Delete an Element From an Array in PHP

When you want to delete an element from an array, you can use the array_splice() that also gives a proper sequence of indexing in the output. Firstly, you have to find the index or key of the given element using the array_search() . After that, you can use the array_splice() function given below to delete an element from an array.

The array_splice() function takes three arguments to pass. The first argument is the array variable. The second argument is the key that is the result of array_search() function. The third argument of the function specifies the number of elements you want to delete from an array. As you have to delete only a single given element from an array. That’s why the third argument is 1.

Источник

Perform Array Delete by Value Not Key in PHP

Perform Array Delete by Value Not Key in PHP

  1. Use the array_search() and unset() Function to Perform Array Delete by Value Not Key in PHP
  2. Use the array_diff() Function to Perform Array Delete by Value Not Key in PHP

This article will introduce different methods to remove value from an array in PHP.

Use the array_search() and unset() Function to Perform Array Delete by Value Not Key in PHP

The main procedure to perform array delete by value, but not a key, is to find the value first. We could delete the value after it is found. We will find the value using array_search() function and delete it using unset() function. The unset() functions resets a variable. The correct syntax to use these functions is as follows.

array_search($value, $array, $strict); 

The built-in function array_search() has three parameters. The details of its parameters are as follows

This function returns the key of the given value.

Syntax of unset()

unset($variable1, $variable2, . , $variableN); 

The built-in function unset() has multiple parameters. The details of its parameters are as follows

This function returns nothing.

Example of Removing Values From an Array in PHP

The program below shows how we can use these functions to perform array delete by value, but not key, in PHP.

php $array = array("Rose","Lili","Jasmine","Hibiscus","Daffodil","Daisy"); echo("Array before deletion: \n"); var_dump($array); $value = "Jasmine"; if (($key = array_search($value, $array)) !== false)   unset($array[$key]); > echo("Array after deletion: \n"); var_dump($array); ?> 
Array before deletion: array(6)   [0]=>  string(4) "Rose"  [1]=>  string(4) "Lili"  [2]=>  string(7) "Jasmine"  [3]=>  string(8) "Hibiscus"  [4]=>  string(8) "Daffodil"  [5]=>  string(5) "Daisy" > Array after deletion: array(5)   [0]=>  string(4) "Rose"  [1]=>  string(4) "Lili"  [3]=>  string(8) "Hibiscus"  [4]=>  string(8) "Daffodil"  [5]=>  string(5) "Daisy" > 

Use the array_diff() Function to Perform Array Delete by Value Not Key in PHP

In PHP, we can also use the array_diff() function to perform array delete by value not key. This function computes the difference of a given array with another array. The correct syntax to use this function is as follows.

Syntax

array_diff($array, $Arr1, $Arr2, . ,$ArrN); 

The program that performs array delete by value, but not key, is as follows.

php $array = array("Rose","Lili","Jasmine","Hibiscus","Daffodil","Daisy"); echo("Array before deletion: \n"); var_dump($array); $value = array("Jasmine"); $array = array_diff( $array, $value); echo("Array after deletion: \n"); var_dump($array); ?> 
Array before deletion: array(6)   [0]=>  string(4) "Rose"  [1]=>  string(4) "Lili"  [2]=>  string(7) "Jasmine"  [3]=>  string(8) "Hibiscus"  [4]=>  string(8) "Daffodil"  [5]=>  string(5) "Daisy" > Array after deletion: array(5)   [0]=>  string(4) "Rose"  [1]=>  string(4) "Lili"  [3]=>  string(8) "Hibiscus"  [4]=>  string(8) "Daffodil"  [5]=>  string(5) "Daisy" > 

Related Article — PHP Array

Copyright © 2023. All right reserved

Источник

Delete array element with value php

  • Different ways to write a PHP code
  • How to write comments in PHP ?
  • Introduction to Codeignitor (PHP)
  • How to echo HTML in PHP ?
  • Error handling in PHP
  • How to show All Errors in PHP ?
  • How to Start and Stop a Timer in PHP ?
  • How to create default function parameter in PHP?
  • How to check if mod_rewrite is enabled in PHP ?
  • Web Scraping in PHP Using Simple HTML DOM Parser
  • How to pass form variables from one page to other page in PHP ?
  • How to display logged in user information in PHP ?
  • How to find out where a function is defined using PHP ?
  • How to Get $_POST from multiple check-boxes ?
  • How to Secure hash and salt for PHP passwords ?
  • Program to Insert new item in array on any position in PHP
  • PHP append one array to another
  • How to delete an Element From an Array in PHP ?
  • How to print all the values of an array in PHP ?
  • How to perform Array Delete by Value Not Key in PHP ?
  • Removing Array Element and Re-Indexing in PHP
  • How to count all array elements in PHP ?
  • How to insert an item at the beginning of an array in PHP ?
  • PHP Check if two arrays contain same elements
  • Merge two arrays keeping original keys in PHP
  • PHP program to find the maximum and the minimum in array
  • How to check a key exists in an array in PHP ?
  • PHP | Second most frequent element in an array
  • Sort array of objects by object fields in PHP
  • PHP | Sort array of strings in natural and standard orders
  • How to pass PHP Variables by reference ?
  • How to format Phone Numbers in PHP ?
  • How to use php serialize() and unserialize() Function
  • Implementing callback in PHP
  • PHP | Merging two or more arrays using array_merge()
  • PHP program to print an arithmetic progression series using inbuilt functions
  • How to prevent SQL Injection in PHP ?
  • How to extract the user name from the email ID using PHP ?
  • How to count rows in MySQL table in PHP ?
  • How to parse a CSV File in PHP ?
  • How to generate simple random password from a given string using PHP ?
  • How to upload images in MySQL using PHP PDO ?
  • How to check foreach Loop Key Value in PHP ?
  • How to properly Format a Number With Leading Zeros in PHP ?
  • How to get a File Extension in PHP ?
  • How to get the current Date and Time in PHP ?
  • PHP program to change date format
  • How to convert DateTime to String using PHP ?
  • How to get Time Difference in Minutes in PHP ?
  • Return all dates between two dates in an array in PHP
  • Sort an array of dates in PHP
  • How to get the time of the last modification of the current page in PHP?
  • How to convert a Date into Timestamp using PHP ?
  • How to add 24 hours to a unix timestamp in php?
  • Sort a multidimensional array by date element in PHP
  • Convert timestamp to readable date/time in PHP
  • PHP | Number of week days between two dates
  • PHP | Converting string to Date and DateTime
  • How to get last day of a month from date in PHP ?
  • PHP | Change strings in an array to uppercase
  • How to convert first character of all the words uppercase using PHP ?
  • How to get the last character of a string in PHP ?
  • How to convert uppercase string to lowercase using PHP ?
  • How to extract Numbers From a String in PHP ?
  • How to replace String in PHP ?
  • How to Encrypt and Decrypt a PHP String ?
  • How to display string values within a table using PHP ?
  • How to write Multi-Line Strings in PHP ?
  • How to check if a String Contains a Substring in PHP ?
  • How to append a string in PHP ?
  • How to remove white spaces only beginning/end of a string using PHP ?
  • How to Remove Special Character from String in PHP ?
  • How to create a string by joining the array elements using PHP ?
  • How to prepend a string in PHP ?

Источник

Читайте также:  What is web start application in java
Оцените статью