values - remove key from associative array php




PHP: Delete an element from an array (20)

unset don't change the index but array_splice does

$arrayName = array( '1' => 'somevalue',
                        '2' => 'somevalue1',
                        '3' => 'somevalue3',
                        500 => 'somevalue500',
                             );


    echo $arrayName['500']; 
    //somevalue500
    array_splice($arrayName, 1,2);

    print_r( $arrayName );
    //Array ( [0] => somevalue [1] => somevalue500 )



    $arrayName = array( '1' => 'somevalue',
                        '2' => 'somevalue1',
                        '3' => 'somevalue3',
                        500 => 'somevalue500',
                             );


    echo $arrayName['500']; 
    //somevalue500
    unset($arrayName[1]);

    print_r( $arrayName );
    //Array ( [0] => somevalue [1] => somevalue500 )

Is there an easy way to delete an element from an array using PHP, such that foreach ($array) no longer includes that element?

I thought that setting it to null would do it, but apparently it does not work.


Associative arrays

For associative arrays, use unset :

$arr = array('a' => 1, 'b' => 2, 'c' => 3);
unset($arr['b']);

// RESULT : array('a' => 1, 'c' => 3)

Numeric arrays

For numeric arrays, use array_splice :

$arr = array(1, 2, 3);
array_splice($arr, 1, 1);

// RESULT : array(0 => 1, 1 => 3)

Note

Using unset for numeric arrays will not produce an error, but it will mess up your indexes :

$arr = array(1, 2, 3);
unset($arr[1]);

// RESULT : array(0 => 1, 2 => 3)

$x = array(1, 2, 3, 4, 5);
var_dump($x);
unset($x[3]); // here is key to be delete
echo '<br>';
array_values($x);
var_dump($x);

unset() destroys the specified variables.

The behavior of unset() inside of a function can vary depending on what type of variable you are attempting to destroy.

If a globalized variable is unset() inside of a function, only the local variable is destroyed. The variable in the calling environment will retain the same value as before unset() was called.

<?php
function destroy_foo() 
{
    global $foo;
    unset($foo);
}

$foo = 'bar';
destroy_foo();
echo $foo;
?>

The Answer of the above code will be bar

To unset() a global variable inside of a function

<?php
function foo() 
{
    unset($GLOBALS['bar']);
}

$bar = "something";
foo();
?>

Remove an array element based on key:

Use unset function like below:

$a = array(
    'salam',
    '10',
    1
);

unset( $a[1] );

print_r( $a );

/*

Output:

Array
(
    [0] => salam
    [2] => 1
)

*/

Remove an array element based on value:

Use array_search function to get element key and use above manner to remove array element like below:

$a = array(
    'salam',
    '10',
    1
);

$key = array_search( 10, $a );

if( $key !== false ) {
    unset( $a[ $key ] );
}

print_r( $a );

/*

Output:

Array
(
    [0] => salam
    [2] => 1
)

*/

Solutions:

  1. To delete one element, use unset( ):
unset($array[3]);
unset($array['foo']);
  1. To delete multiple noncontiguous elements, also use unset( ):
unset($array[3], $array[5]);
unset($array['foo'], $array['bar']);
  1. To delete multiple contiguous elements, use array_splice( ):
array_splice($array, $offset, $length);

Further explanation:

Using these functions removes all references to these elements from PHP. If you want to keep a key in the array, but with an empty value, assign the empty string to the element:

$array[3] = $array['foo'] = '';

Besides syntax, there's a logical difference between using unset( ) and assigning '' to the element. The first says This doesn't exist anymore, while the second says This still exists, but its value is the empty string.

If you're dealing with numbers, assigning 0 may be a better alternative. So, if a company stopped production of the model XL1000 sprocket, it would update its inventory with:

unset($products['XL1000']);

However, if it temporarily ran out of XL1000 sprockets, but was planning to receive a new shipment from the plant later this week, this is better:

$products['XL1000'] = 0;

If you unset( ) an element, PHP adjusts the array so that looping still works correctly. It doesn't compact the array to fill in the missing holes. This is what we mean when we say that all arrays are associative, even when they appear to be numeric. Here's an example:

// create a "numeric" array
$animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');
print $animals[1];  // prints 'bee'
print $animals[2];  // prints 'cat'
count($animals);    // returns 6

// unset( )
unset($animals[1]); // removes element $animals[1] = 'bee'
print $animals[1];  // prints '' and throws an E_NOTICE error
print $animals[2];  // still prints 'cat'
count($animals);    // returns 5, even though $array[5] is 'fox'

// add new element
$animals[ ] = 'gnu'; // add new element (not Unix)
print $animals[1];  // prints '', still empty
print $animals[6];  // prints 'gnu', this is where 'gnu' ended up
count($animals);    // returns 6 

// assign ''
$animals[2] = '';   // zero out value
print $animals[2];  // prints ''
count($animals);    // returns 6, count does not decrease

To compact the array into a densely filled numeric array, use array_values( ):

$animals = array_values($animals);

Alternatively, array_splice( ) automatically reindexes arrays to avoid leaving holes:

// create a "numeric" array
    $animals = array('ant', 'bee', 'cat', 'dog', 'elk', 'fox');
    array_splice($animals, 2, 2);
    print_r($animals);
    Array
    (
        [0] => ant
        [1] => bee
        [2] => elk
        [3] => fox
    )

This is useful if you're using the array as a queue and want to remove items from the queue while still allowing random access. To safely remove the first or last element from an array, use array_shift( ) and array_pop( ), respectively.


Follow default functions

i)

$Array = array("test1","test2","test3","test3");

unset($Array[2]);

ii)

$Array = array("test1","test2","test3","test3");

array_pop($Array);

iii)

$Array = array("test1","test2","test3","test3");

array_splice($Array,1,2);

iv)

$Array = array("test1","test2","test3","test3");

array_shift($Array);

For associative arrays, with non integer keys:

Simply, unset($array[$key]) would work.

For arrays having integer keys and if you want to maintain your keys:

  1. $array = [ 'mango', 'red', 'orange', 'grapes'];

unset($array[2]); $array = array_values($array);

  1. array_splice($array, 2, 1);

If you have a numerically indexed array where all values are unique (or they are non-unique but you wish to remove all instances of a particular value), you can simply use array_diff() to remove a matching element, like this:

$my_array = array_diff($my_array, array('Value_to_remove'));

For example:

$my_array = array('Andy', 'Bertha', 'Charles', 'Diana');
echo sizeof($my_array) . "\n";
$my_array = array_diff($my_array, array('Charles'));
echo sizeof($my_array);

This displays the following:

4
3

In this example, the element with the value 'Charles' is removed as can be verified by the sizeof() calls that report a size of 4 for the initial array, and 3 after the removal.


If you have to delete multiple values in an array and the entries in that array are objects or structured data, [array_filter][1] is your best bet. Those entries that return a true from the callback function will be retained.

$array = [
    ['x'=>1,'y'=>2,'z'=>3], 
    ['x'=>2,'y'=>4,'z'=>6], 
    ['x'=>3,'y'=>6,'z'=>9]
];

$results = array_filter($array, function($value) {
    return $value['x'] > 2; 
}); //=> [['x'=>3,'y'=>6,z=>'9']]

It should be noted that unset() will keep indexes untouched, which is what you'd expect when using string indexes (array as hashtable), but can be quite surprising when dealing with integer indexed arrays:

$array = array(0, 1, 2, 3);
unset($array[2]);
var_dump($array);
/* array(3) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [3]=>
  int(3)
} */

$array = array(0, 1, 2, 3);
array_splice($array, 2, 1);
var_dump($array);
/* array(3) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(3)
} */

So array_splice() can be used if you'd like to normalize your integer keys. Another option is using array_values() after unset():

$array = array(0, 1, 2, 3);

unset($array[2]);
$array = array_values($array);
var_dump($array);
/* array(3) {
  [0]=>
  int(0)
  [1]=>
  int(1)
  [2]=>
  int(3)
} */

Suppose you have such an array:

Array
(
    [user_id] => 193
    [storage] => 5
)

To delete storage, do:

unset($attributes['storage']);
$attributes = array_filter($attributes);

And you get:

Array
(
    [user_id] => 193
)

This may help...

<?php
    $a1=array("a"=>"red","b"=>"green","c"=>"blue","d"=>"yellow");
    $a2=array("a"=>"purple","b"=>"orange");
    array_splice($a1,0,2,$a2);
    print_r($a1);
    ?>

result will be:

Array ( [0] => purple [1] => orange [c] => blue [d] => yellow )

To avoid doing a search one can play around with array_diff:

$array = array(3, 9, 11, 20);
$array = array_diff($array, array(11) ); // removes 11

In this case one doesn't have to search/use the key.


You can simply use unset() to delete an array.

Remember that array must be unset after foreach function.


  // our initial array  
   $arr = array("blue", "green", "red", "yellow", "green", "orange", "yellow", "indigo", "red");  
  print_r($arr);

  // remove the elements who's values are yellow or red  
   $arr = array_diff($arr, array("yellow", "red"));
  print_r($arr);  

This is the output from the code above:

Array
(
    [0] => blue
    [1] => green
    [2] => red
    [3] => yellow
    [4] => green
    [5] => orange
    [6] => yellow
    [7] => indigo
    [8] => red
)

Array
(
    [0] => blue
    [1] => green
    [4] => green
    [5] => orange
    [7] => indigo
)

Now, array_values() will reindex a numerical array nicely, but will remove all key strings from the array and replace them with numbers. If you need to preserve the key names (strings), or reindex the array if all keys are numerical, use array_merge():

$arr = array_merge(array_diff($arr, array("yellow", "red")));
print_r($arr);

outputs

Array
(
    [0] => blue
    [1] => green
    [2] => green
    [3] => orange
    [4] => indigo
)

$key = array_search($needle,$array);
if($key!==false){
    unset($array[$key]);
}

<?php
    $stack = array("fruit1", "fruit2", "fruit3", "fruit4");
    $fruit = array_shift($stack);
    print_r($stack);

    echo $fruit;
?>

Output:

Array
(
    [0] => fruit2
    [1] => fruit3
    [2] => fruit4
)

fruit1

<?php 
//If you want to remove a particular array element use this method
$my_array = array("key1"=>"value 1","key2"=>"value 2","key3"=>"value 3");

print_r($my_array);
if(array_key_exists("key1",$my_array)){  
unset($my_array['key1']);
print_r($my_array);
}else{
echo "Key does not exist";
}
?>

<?php 
//To remove first array element
$my_array = array("key1"=>"value 1","key2"=>"value 2","key3"=>"value 3");
print_r($my_array);
$new_array=array_slice($my_array,1); 
print_r($new_array);
?>


<?php 
echo "<br/> ";
//To remove first array element to length
//starts from first and remove two element 
$my_array = array("key1"=>"value 1","key2"=>"value 2","key3"=>"value 3");
print_r($my_array);
$new_array=array_slice($my_array,1,2); 
print_r($new_array);
?>

Output

 Array ( [key1] => value 1 [key2] => value 2 [key3] => 
 value 3 ) Array (    [key2] => value 2 [key3] => value 3 ) 
 Array ( [key1] => value 1 [key2] => value 2 [key3] => value 3 ) 
 Array ( [key2] => value 2 [key3] => value 3 )
 Array ( [key1] => value 1 [key2] => value 2 [key3] => value 3 ) 
 Array ( [key2] => value 2 [key3] => value 3 ) 

// Remove by value
function removeFromArr($arr, $val)
{
    unset($arr[array_search($val, $arr)]);
    return array_values($arr);
}




arrays