How can I find out if an array has values for specific positions AND everything else is empty?
Let's say I want to check indexes 2,3,4
If I have this array:
10,3,56,78,89,89
returns false
if I have ,,45,56,67,,
returns true
How can I do this in PHP
?
Asked
Active
Viewed 42 times
-2

Pedro Lobito
- 94,083
- 31
- 258
- 268

MalcolmInTheCenter
- 1,376
- 6
- 27
- 47
-
1Please **clarify your specific problem or add additional details to highlight exactly what you need**. As it's currently written, itβs hard to tell exactly what you're asking. See the [How to Ask](http://stackoverflow.com/help/how-to-ask) page for help clarifying this question β Pedro Lobito May 03 '17 at 01:41
2 Answers
1
Try this out (considering we're inside of function)
$allowed = [2, 3, 4];
$arr = [NULL, NULL, 45, 56, 67, NULL, NULL];
foreach($arr as $k => $v)
if(!empty($v) && !in_array($k, $allowed)) return false;
return true;

Nikolay 'Alagunto' Tkachenko
- 813
- 8
- 19
-
Note: if you have string like $str = "13,15,,60", explode(",", $str) will convert it into an array β Nikolay 'Alagunto' Tkachenko May 03 '17 at 01:43
-
1
This works well for you. array compare, array_keys(), array_filter()
return [2,3,4] == array_keys(array_filter($array)) ? true : false;