-1

I have an array like this:

Array
(
    [44] => 2
    [21] => 2
    [] => 2
    [27] => 2
)

How to find and remove (unset) keys without specified names? So in this case array should look like this:

Array
(
    [44] => 2
    [21] => 2
    [27] => 2
)
dbx
  • 133
  • 18
  • How you add values to the array? all keys need to be name. if you add value as $array[] = 2 then key will be the next key by count, or 0. – Evgeniy Belov Oct 09 '18 at 06:58
  • The key is just `''` no? Create a new array, do a foreach on first array, add value on new array if key is not empty...Maybe there is a php array function but don't know it. And how do you get this value? Can you have multiple empty key? – Mickaël Leger Oct 09 '18 at 06:59
  • @Evgeniy Belov I do not create this array - this is what i get from external source :/ – dbx Oct 09 '18 at 07:01
  • Possible duplicate of [PHP: Delete an element from an array](https://stackoverflow.com/questions/369602/php-delete-an-element-from-an-array) – mickmackusa Oct 09 '18 at 12:31
  • A php array cannot have more than one element with the same key. A single `unset()` is all that is required. – mickmackusa Oct 09 '18 at 12:32

5 Answers5

2

could be the key is '' (empty string)

in this case assuming you have

   $myArray = [
    [44] => 2,
    []   => 2,
    [21] => 2,
    [27] => 2,
   ]

then try unset

 unset($myArray['']);
ScaisEdge
  • 131,976
  • 10
  • 91
  • 107
1

it seems that you have an array (key-value) in this type of arrays we have a key, and its not possible to have a cell without any key. so as you mentioned in your question, the cell which seem that has not any key, already has the ''(empty string) key. i mean its definition has been like this

$array['']=2;

so you can simply unset it as normal. like this

unset( $array['']);

because if you define a cell as bellow:

 $array[]=2;

automatically it gives the first available numerical key. for example if you have:

 $array[4]=5;
 $array[]=6;

it automatically gives the next free index , it means to php like this:

 $array[4]=5;
 $array[5]=6;

i hope it can help you.

0
if (($key = array_search(null', $array)) !== false) {
    unset($array[$key]);
}

I suggest you to read this thread

Ascaliko
  • 76
  • 1
  • 9
0

I think that the best solution will be the simplest one:

$array = [
44 => 2,
21 => 2,
'' => 2,
27 => 2
];

$results = [];

foreach ($array as $k => $a) {
    if (!empty($k)) {
        $results[$k] = $a;
    }
}

var_dump($results);

sandbox

rad11
  • 1,561
  • 3
  • 15
  • 30
-1

You could try this:

$arrayWithoutNullKeyMembers = array_filter($arrayWithNullKeyMembers,
                        function($key){ return !empty($key); }, ARRAY_FILTER_USE_KEY);
apnmrv
  • 21
  • 3