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]);
PHP - Delete element from multidimensional-array based on value - Stack Overflow
PHP: remove element from multidimensional array (by key) using foreach - Stack Overflow
php - Deleting key from expanding multidimensional array - Stack Overflow
Remove key from multidimensional array in PHP - Stack Overflow
Have a look at the // comments
foreach ($array_leave_dates as
leave_type) {
// you treat $leave_type as array here
foreach ($leave_type as $leave_dates) {
// you treat $leave_type as string here
// doesn't feel right
if($leave_type == 'Maternity Leave') {
// you are unsetting with a value
//unset($array_leave_dates[ --> $leave_type <-- ]);
// i assume you want to delete the key
unset($array_leave_dates[$emp]);
}
else{
// $row doesn't seem to exist, looks wrong from here
echo $leave_dates[$row];
}
}
}
Not sure what your data source looks like:
<?php
// Remove the whole employee
$employees = array(
'emp1' => array('sick' => 'Mon - Tue'),
'emp2' => array('bun in oven' => '2016 - 2017'),
'emp3' => array('broken heart' => '2017 - ∞'),
);
foreach ($employees as
leave) {
foreach ($leave as $leaveName => $date) {
if($leaveName == 'bun in oven') {
unset($employees[$emp]);
}
}
}
print_r($employees);
// OR remove only 'Maternity' from the employee but keep everything else
<?php
$employees = array(
'emp1' => array('sick' => 'Mon - Tue', 'its friday and im not coming in' => 'Fri'),
'emp2' => array('bun in oven' => '2016 - 2017', 'sick' => 'Thu'),
'emp3' => array('broken heart' => '2017 - ∞'),
);
foreach ($employees as
leave) {
foreach ($leave as $leaveName => $date) {
if($leaveName == 'bun in oven') {
unset($employees[
leaveName]);
}
}
}
print_r($employees);
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>.
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;
}
}
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.");
}
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;
}
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.
The following code works (and doesn't use deprecated stuff), just tested it:
function traverseArray(&$array, $keys) {
foreach ($array as $key => &$value) {
if (is_array($value)) {
traverseArray($value, $keys);
} else {
if (in_array($key, $keys)){
unset($array[$key]);
}
}
}
}
You could use pass by reference, declare your function like this:
function traverseArray(&$array, $keys)
{
foreach($array as $key=>$value)
{
if(is_array($value))
{
traverseArray($value, $keys);
}else{
if(in_array($key, $keys)){
unset($array[$key]);
}
}
}
}
then you can unset the key and it will vanish from the original passed value too since the $array in the function is merely a pointer to the array you passed so it updates that array.
unset($array[$key]);
For more information check the php documentation on passing by reference
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. –