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
Discussions

PHP - Delete element from multidimensional-array based on value - Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most · Connect and share knowledge within a single location that is structured and easy to search More on stackoverflow.com
🌐 stackoverflow.com
April 21, 2017
PHP: remove element from multidimensional array (by key) using foreach - Stack Overflow
I got multidimensional array. From each subarray, I would like to remove / unset values with index 1. My array $data. Array ( [3463] => Array ( [0] => 1 [... More on stackoverflow.com
🌐 stackoverflow.com
php - Deleting key from expanding multidimensional array - Stack Overflow
I've got an array that keeps expanding when I add values to it, and I'm trying to write a function to remove a specific value from a key, This is what the array looks like currently Array ( ... More on stackoverflow.com
🌐 stackoverflow.com
Remove key from multidimensional array in PHP - Stack Overflow
Hi I am going to make tree array for multilevel category menu and I have found the solution from below link: stackoverflow answer But my problem is that i am getting output of my array as FOR... More on stackoverflow.com
🌐 stackoverflow.com
🌐
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.
🌐
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 › questions › 48455358 › deleting-key-from-expanding-multidimensional-array
php - Deleting key from expanding multidimensional array - Stack Overflow
For example, we could interpret ... case the function could look like this: function deleteKey($array, $key) { if( isset($array[$key]) ) { unset($array[$key]); return $array; } foreach($array as $k => $value) { $return[$k] ...
Find elsewhere
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;
    }
}
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 = 0; $i <= $c; ++$i) {
    // Make sure the index to go down for deletion actually exists.
    if (array_key_exists($indices[$i], $a)) {
      // This is the target if we reached the last index that was passed.
      if ($i === $c) {
        unset($a[$indices[$i]]);
      }
      // Make sure we have an array to go further down.
      elseif (is_array($a[$indices[$i]])) {
        $a =& $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[$i], $a)) {
      if ($i === $c) {
        unset($a[$indices[$i]]);
        return $array;
      }
      elseif (is_array($a[$indices[$i]])) {
        $a =& $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 = 0; $i < $qtd_indexes; $i++) {
        if ( ! array_key_exists($indexes[$i], $array)) {
          throw new \Exception($indexes[$i] . " doesn't exist");
        }

        // Check if it is the target entry
        if ($i === $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;
}
🌐
ItSolutionstuff
itsolutionstuff.com › post › how-to-remove-multiple-keys-from-php-arrayexample.html
How to Remove Multiple Keys from PHP Array? - ItSolutionstuff.com
May 14, 2024 - But we will create our own php custom function and remove all keys by given array value. In this example i created custom function as array_except(). you need to pass one main array and another will be keys array that you want to remove it. ... I hope it can help you... ... I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.📺 Subscribe on YouTube
🌐
W3Schools
w3schools.com › php › php_arrays_remove.asp
PHP Remove Array Items
Note: The array_diff() function takes values as parameters, and not keys.
🌐
NiceSnippets
nicesnippets.com › blog › how-to-remove-empty-array-from-multidimensional-array-in-php
How to Remove Empty Array from MultiDimensional ...
April 3, 2023 - Disclaimer: References to any specific company, product or services on this Site are not controlled by GoDaddy.com LLC and do not constitute or imply its association with or endorsement of third party advertisers
🌐
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 ·