Leo Tahk
Leo Tahk

Reputation: 420

PHP. Cannot read a key with zero suffix

I have an array of items

$items['list'] = 

    Array
    (
        [item_0] => Array
            (
                [name] => aaa
                [lvl] => 1
            )

        [item_1] => Array
            (
                [name] => bbb
                [lvl] => 1
            )

        [item_2] => Array
            (
                [name] => ccc
                [lvl] => 1
            )

I can print it, but when im trying to print

print_r($items['list']['item_0']);

I get an error Notice: Undefined index: item_0
Is there something special about the zero suffix?
The rest of the keys work fine.

and if I do

$a = array_keys($items['list']);

var_dump($a[0]);

It says it's a string with 9 characters.

string(9) "item_0" 


The issue comes when i open the file in windows notepad and save it. The notepad's UTF-8 is UTF-8 BOM, which adds characters to the string.
I would vote to delete the quastion, as the issue is caused by unneeded actions which change encoding. Sorry for wasting your time.

Upvotes: 0

Views: 112

Answers (1)

Andreas
Andreas

Reputation: 23958

Most likely there is a special character in there.
It could be a new line character or a invisible character.

A fix is to foreach the array and create a new array with correct characters.

$i = 0;
foreach($items['list'] as $val){
    $new["item_" . $i] = $val;
    $i++;
}


Other possible solution is to use the key but trim it. That could remove extra characters.

foreach($items['list'] as $key => $val){
    $new[trim($key)] = $val;
}


Since OP keeps refusing to answer my questions I add a guess answer.
Use preg_grep to grab the key names based on what characters is allowed.

I follow the example I got in the question which means a-Z 0-9 and underscore.
If more is needed then it can easily be added.

//Match key names
$keys = preg_grep("/[a-zA-Z0-9_]+/", array_keys($items['list']));
// Use array_combine to overwrite the current keys.
$items['list'] = array_combine($keys, $items['list']);

Upvotes: 2

Related Questions