I have multiple array having the last index with 0 value and needs to remove that specific index. how can I do that in PHP? Thanks
Asked
Active
Viewed 489 times
-4
-
2Pleas share what you have tried so far and why this did not work, see https://stackoverflow.com/help/how-to-ask – Sven Hakvoort Jan 21 '19 at 09:26
-
2Have you tried anything? A loop and `array_filter` would work. – Sougata Bose Jan 21 '19 at 09:26
-
1do you always need to remove the index `2` or sometimes its some other index? – Red Bottle Jan 21 '19 at 09:26
-
Red Bottle, No its not .. it can be 3, 4 but its alwas the last index. – Zaker Husien Yusofi Jan 21 '19 at 09:28
-
You can user array_filter function : array_filter($arr); // removing blank, null, false, 0 (zero) values http://php.net/manual/en/function.array-filter.php – Abhinav Verma Jan 21 '19 at 09:33
-
1Possible duplicate of [PHP: Delete an element from an array](https://stackoverflow.com/questions/369602/php-delete-an-element-from-an-array) – Sven Hakvoort Jan 21 '19 at 10:01
2 Answers
2
If you are looking for a Laravel way of doing it, you could achieve this with Collections.
$data = [
'edu_country' => ['1', '11', '0'],
'edu_grade' => ['1', '1', '0']
];
return collect($data)->map(function($value) {
return collect($value)->reject(function($value, $key) {
return $value === '0';
})->toArray();
})->toArray();
There might be an easier way of doing this with a Collection as well. I need to research a bit more.

Mozammil
- 8,520
- 15
- 29
1
You can use array_filter
. Reference : php.net/manual/en/function.array-filter.php
// Select only non-zero value indices
$newArray = array_filter($originalArray, function ($a) {
return $a != 0;
});

Sreejith BS
- 1,183
- 1
- 9
- 18
-
This does not work since it is a multidimensional array so your $a is the nested array and not the value "0" – Sven Hakvoort Jan 21 '19 at 10:03
-