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 Overflowarray_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; });
There are a lot of weird array functions in PHP, but many of these requests are solved with very simple foreach loops...
$value = 15;
foreach ($cart as
v) {
if (
value) {
unset($cart[$i]);
}
}
If $value is not in the array at all, nothing will happen. If $value is in the array, the entire index will be deleted (unset).
There's really no reason for unset to not work (assuming that's what you meant by "I am not able to implement in my case") unless you did it like this:
foreach ($array['answers'] as $answer) {
unset($answer['image'];
}
It can't work that way, because the $answer you have there does not refer to the original array. It's a copy of the item, because the foreach loop makes a copy of each value in the array as it goes.
You need to get the key of the outer array and use that as well in your unset expression.
foreach ($array['answers'] as
answer) {
unset($array['answers'][$key]['image'];
}
You can just use the unset E.g.: If you want to remove the index 1, with the second answer, you could just do
unset($answers[1]);
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.");
}
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;
}
You can't use array_filter() for this purpose. Use array_reduce() instead
$newArr = array_reduce($array, function($carry, $item){
$carry[] = [$item[0], $item[2]];
return $carry;
});
Check result in demo
You can't use array_filter for this. array_filter processes the values, but you want to remove a specific key.
Use array_splice() to remove an index and have all following increments adjust.
foreach ($array as &$element) {
array_splice($element, 1, 1);
}
The & makes this a reference variable, so modifying the variable affects the elements in the array.
Try this:
function removeElementWithValue($array, $key, $value){
foreach ($array as $subKey => $subArray) {
if ($subArray[$key] == $value) {
unset($array[$subKey]);
}
}
return $array;
}
Then you would call it like this:
$array = removeElementWithValue($array, "year", 2011);
Try this:
function remove_element_by_value($arr, $val) {
$return = array();
foreach($arr as $k => $v) {
if(is_array($v)) {
$return[$k] = remove_element_by_value($v, $val); //recursion
continue;
}
if($v == $val) continue;
$return[$k] = $v;
}
return $return;
}
Both arrays are more are like same..
Format-1 looks print_r($yourarray); version
Format-2 looks like var_export($yourarray); version.
You need to have a look at the debugger functions.. print_r(), var_dump() and var_export().
If your purpose is debugging you may use <pre>var_dump()</pre>.
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 .
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']]);
try this,
array_map(function($v){array_pop($v); return $v;}, $array);
Note, array_pop pop the last element of array. if the distance is not the last key, you can use unset() instead
foreach ($mainArray as $key => $mainData){
foreach ($subArray as $subData){
if($mainData['distance'] == $subData['distance']){
unset($mainArray[$key]); break;
}
}
}
Try this way. –
function unset_num_keys($array)
{
$array_out = array();
foreach($array AS $k => $v)
{
if(is_array($v)) //value is an array, so clean it
{
$array_out[$k] = unset_num_keys($v); //clean "child" arrays
}
elseif(!is_numeric($k))
{
$array_out[$k] = $v; // key is "safe"
}
}
return $array_out;
}
Then
$clean_array = unset_num_keys($old_array);
Loop threw the array and if the key(index) is numeric then remove that item from the array.
foreach($level1_array as &$arr){
foreach ($arr as $key => $value) {
if (is_int($key)) {
unset($arr[$key]);
}
}
}
Example
<?php
$level1_array = array(
array(
"smith",
"name" => "smith",
"20",
"age"=>20
),
array(
"smith",
"name" => "smith",
"20",
"age"=>20
),
array(
"smith",
"name" => "smith",
"20",
"age"=>20
),
);
foreach($level1_array as &$arr){
foreach ($arr as $key => $value) {
if (is_int($key)) {
unset($arr[$key]);
}
}
}
var_dump($level1_array);
?>
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>';
?>
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;
}
}