array_filter is great for removing things you don't want from arrays.

$cart = array_filter($cart, function($x) { return $x['id'] != 15; });

If you want to use a variable to determine which id to remove rather than including it in the array_filter callback, you can use your variable in the function like this:

$value = 15;
$cart = array_filter($cart, function(value) { return value; });
Answer from Don't Panic on Stack Overflow
🌐
PHP
php.net › manual › en › function.array-keys.php
PHP: array_keys - Manual
I ended up with this (returns the array itself if no further parameter than the array is given, false with no params - does not change the source array) usage: array_remove(array $input [, mixed key ...]) <?php function array_remove() { if ($stack ...
🌐
GitHub
gist.github.com › jeankassio › 841d1e71f28dc8175b14a3ff5ad804fb
PHP - search and remove any index of multidimensional array · GitHub
PHP - search and remove any index of multidimensional array · Raw · remove_array_key.php · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Stack Overflow
stackoverflow.com › q › 46445164
php - Remove key in multidimensional array - Stack Overflow
function remove_key($array, $key) { foreach($array as $k => $v) { if(is_array($v)) { $array[$k] = remove_key($v, $key); } elseif($k == $key) { unset($array[$k]); } } return $array; } $array = remove_key($array,'Price'); ... Save this answer.
Top answer
1 of 3
3

No need for eval() with a little bit of referencing.

/**
 * Remove index from multi-dimensional array.
 *
 * @param array $array
 *   The array to remove the index from.
 * @param array $indices
 *   Indexed array containing the indices chain up to the index that should be
 *   removed.
 * @return
 *   The array with the index removed.
 * @throws \InvalidArgumentException
 *   If the index does not exist within the array.
 */
function removeByIndex(array $array, array $indices) {
  // Create a reference to the original array.
  $a =& $array;

  // Count all passed indices, remove one because arrays are zero based.
  $c = count($indices) - 1;

  // Iterate over all passed indices.
  for (i <= i) {
    // Make sure the index to go down for deletion actually exists.
    if (array_key_exists($indices[a)) {
      // This is the target if we reached the last index that was passed.
      if (c) {
        unset(indices[$i]]);
      }
      // Make sure we have an array to go further down.
      elseif (is_array(indices[$i]])) {
        $a =& indices[$i]];
      }
      // Index does not exist since there is no array to go down any further.
      else {
        throw new \InvalidArgumentException("{$indices[$i]} does not exist.");
      }
    }
    // Index does not exist, error.
    else {
      throw new \InvalidArgumentException("{$indices[$i]} does not exist.");
    }
  }

  return $array;
}

print_r(removeByIndex(
  [ "test1" => [ "test2" => [ "test3" => "test" ] ], "test4" => "test" ],
  [ "test1", "test2", "test3" ]
));

Since I mentioned it in the comments, one could (micro-)optimize the function, but I advice against it, since it is less readable and might confuse some programmers.

<?php

function removeByIndex(array $array, array $indices) {
  $a =& $array;
  $c = count($indices) - 1;
  $i = 0;
  do {
    if (array_key_exists($indices[a)) {
      if (c) {
        unset(indices[$i]]);
        return $array;
      }
      elseif (is_array(indices[$i]])) {
        $a =& indices[$i]];
      }
      else break;
    }
    else break;
  }
  while (++$i);
  throw new \InvalidArgumentException("{$indices[$i]} does not exist.");
}
2 of 3
1

Based on the briliant @Fleshgrinder answer, i am using this final version:

function removeByIndex($vars, $indexes) {
    if ( ! is_array($indexes)) {
        throw new \Exception('Array expected');
    }

    $array = & $vars;

    $qtd_indexes = count($indexes);

    for (i < $qtd_indexes; $i++) {
        if ( ! array_key_exists($indexes[array)) {
          throw new \Exception($indexes[$i] . " doesn't exist");
        }

        // Check if it is the target entry
        if (qtd_indexes - 1) {
            unset($array[$indexes[$i]]);
        } elseif (is_array($array[$indexes[$i]])) { // Check if exists one more level
            $array = & $array[$indexes[$i]];
        } else {
            // If it isn't the target and it isn't an array, throw exception
            throw new \Exception("Content of '" . $indexes[$i] . "' isn't an array");
        }
    }

    return $vars;
}
Find elsewhere
Top answer
1 of 3
1

An easy utility to avoid removing array keys that do not exist by accident:

function removeArrayKey($path, &$array ) {

    $array_temp = &$array;
    $previousItem = null;

    $path_bits = explode( ".", $path );

        foreach( $path_bits as &$path_bit ) {

           if( !isset( $array_temp[ $path_bit ] ) ) {
                  die("Error" . $path_bit);
                   //throw new Exception( "Path does not exist in array" );
            }

            $previousItem = &$array_temp;
            $array_temp = &$array_temp[ $path_bit ];

        }

        if( isset( $previousItem ) ) {

             unset( $previousItem[ $path_bit ] );

        }

        return $array;

}

To use the function, simply use removeArrayKey( "cars.mercedes.cars", $array_1 ); and separate each array index with a .

2 of 3
0

So as i see your problem, you'd like to save your array path into a variable. You can solve this problem on two different ways:

Save every key into a variable

The way i would do it, if my array structure looks always the same (e.g. [cars][type][model]). You can save the key to delete into a variable:

$cars = 'cars';
$type = 'audi';
$model = 'a5';

unset($array_1[$cars][$type][$model]);

This will work excellent in a for(each) loop.

Saving your keys into an array

This method will save your problem, but it is not the best option. You can save all the keys you like to unset into an array. This way can cause many bugs and you should reconsider your array structure, if this way is your solution.

// arrays start at 0
$to_unset = [
    0 => 'cars',
    1 => 'audi',
    2 => 'a5',
];

unset($array_1[$to_unset[0]][$to_unset[1]][$to_unset[2]]);

An other possible option here is to name the keys of the $to_unset array.

// arrays start at 0
$to_unset = [
    'cars' => 'cars',
    'type' => 'audi',
    'model' => 'a5',
];

unset($array_1[$to_unset['cars']][$to_unset['type']][$to_unset['model']]);
🌐
Stack Overflow
stackoverflow.com › questions › 27481606 › remove-array-key-from-multidimensional-array › 27481704
php - Remove array key from multidimensional array - Stack Overflow
$array['flightOne']['abc']['2014-12-15'] = array_merge($array['flightOne']['abc']['2014-12-15'], $array['flightOne']['ghi']['2014-12-15']); unset($array['flightOne']['ghi']);
🌐
Stack Overflow
stackoverflow.com › questions › 48455358 › deleting-key-from-expanding-multidimensional-array
php - Deleting key from expanding multidimensional array - Stack Overflow
Since $array has only key 0 and 1, that results in false. Now we loop through $array. The first thing we find is: ... On that input, DeleteKey get invoked again. This time, the key 'a' is found. It is removed, and ['b' => 'Hello'] is returned. Since ['b' => 'Hello'] does not equal null, the loop breaks here.
Top answer
1 of 2
1

This seems to work:

<?php

$myarray = array (
  0 => 
  array (
    'inf:name' => 'aaa',
    'inf:value' => '111',
    'inf:children' => NULL,
  ),
  1 => 
  array (
    'inf:name' => 'bbb',
    'inf:value' => '222',
    'inf:children' => NULL,
  ),
  2 => 
  array (
    'inf:name' => 'ccc',
    'inf:value' => '333',
    'inf:children' => NULL,
  ),
  3 => 
  array (
    'inf:name' => 'bob',
    'inf:children' => 
    array (
      0 => 
      array (
        'inf:name' => 'ddd',
        'inf:value' => '444',
        'inf:children' => NULL,
      ),
    ),
  ),
  4 => 
  array (
    'inf:name' => 'data',
    'inf:children' => 
    array (
      0 => 
      array (
        'inf:name' => 'eee',
        'inf:value' => '555',
        'inf:children' => NULL,
      ),
      1 => 
      array (
        'inf:name' => 'steve',
        'inf:value' => 'bar1',
        'inf:children' => NULL,
      ),
      2 => 
      array (
        'inf:name' => 'john',
        'inf:value' => 'bar2',
        'inf:children' => NULL,
      ),
      3 => 
      array (
        'inf:name' => 'peter',
        'inf:value' => 'bar3',
        'inf:children' => 
        array (
          0 => 
          array (
            'inf:name' => 'fff',
            'inf:value' => '666',
            'inf:children' => NULL,
          ),
        ),
      ),
    ),
  ),
);





function array_cleanup($array, $todelete ) {
    foreach ($array as $key => $value) {
        if (is_array($value)) {
            if (in_array($value['inf:name'], $todelete)) {
                unset($array[$key]);
            } else {
                $array[$key] = array_cleanup($array[$key], $todelete);
            }
        }
    }
    return $array;
}



$newarray = array_cleanup($myarray, array("aaa", "peter", "ccc"));
$newarray = array_values($newarray);

echo '<pre>';
var_export($newarray);
echo '</pre>';

?>
2 of 2
0
class Arr
{
    /**
     * Removes all occurences of {needle} in {subject}
     *
     * @return array
     */
    public static function purgeKey(string $needle, array $subject) : array
    {
        foreach ($subject as $key => $value) {
            if (is_array($value)) {
                $subject[$key] = static::purgeKey($needle, $value);
            } else if ($key === $needle) {
                unset($subject[$needle]);
            }
        }

        return $subject;
    }
}
🌐
GeeksforGeeks
geeksforgeeks.org › php › how-to-delete-an-array-element-based-on-key-in-php
How to Delete an Array Element based on Key in PHP? - GeeksforGeeks
July 11, 2025 - Below are the approaches to deletean Array element based on key in PHP: ... The unset() function is used to remove element from the array. The unset function is used to destroy any other variable and same way use to delete any element of an array.
🌐
PHP Freaks
forums.phpfreaks.com › php coding › php coding help
Remove related element from multidimensional array - PHP Coding Help - PHP Freaks
May 23, 2018 - array · By thara May 22, 2018 in PHP Coding Help · Share · https://forums.phpfreaks.com/topic/307295-remove-related-element-from-multidimensional-array/ More sharing options... Followers 1 · Go to solution Solved by Barand, May 22, 2018 · Reply to this topic ·