S.M. Pat
S.M. Pat

Reputation: 311

Can not acces array value in php

Have an php array made from POST data $this->log->write(print_r($array , true));

Array
(
[accept] => */*
[accept-encoding] => gzip, deflate
[signature] =>    37df88b6f845c21b1cda84cf3d3b94b0b15759b74f7387ceb0e9c8a6247c211f
[connection] => keep-alive
[content-length] => 610
[user-agent] => python-requests/2.10.0
)

$this->log->write(var_export($array , true).'var_export');

 array (
'accept' . "\0" . '' => '*/*',
'accept-encoding' . "\0" . '' => 'gzip, deflate',
'signature' . "\0" . '' => '37df88b6f845c21b1cda84cf3d3b94b0b15759b74f7387ceb0e9c8a6247c211f',
'connection' . "\0" . '' => 'keep-alive',
'content-length' . "\0" . '' => '610',
'user-agent' . "\0" . '' => 'python-requests/2.10.0',
)var_export

The problem I can not access array value with $array['signature']; it is empty.

Sorry question looks nub but it is not. Work with arrays before and no problem. Have tried this as well $array["signature"]; $array->signature; empty returned. Please help

Upvotes: 4

Views: 104

Answers (2)

Abhay Maurya
Abhay Maurya

Reputation: 12277

You can access it as:

$array["signature\0"];

"\0" is called "NULL character", even though it will not be visible in outputting the array but it makes difference while accessing the index.

That's why "signature" and "signature\0" are not same even if they both will output 'signature' as later one has 10 characters while former has only 9 which makes it different while using it as an index.

If you are familiar with C then you can take reference from there that "\0" is used to end a string otherwise variable is consider as array of character instead of string.

As given in another answer, sanitization of keys can be another alternative. But i would rather use foreach to do so:

foreach($array as $key=>$val){unset($array[$key]);$array[trim($key)] = $val;}
echo $array['signature'];

It won't need two steps for sanitizing and assigning. It works in one.

I hope it helps

Upvotes: 1

Bobot
Bobot

Reputation: 1118

As you can see, your keys are append somehow with \0 (which is end string character in C if my memory is good)

Thats why when you try to gather key signature there is nothing, because the key is signature\0

So, you have two solutions, first is calling $array['signature' . "\0"] second is doing an array key sanitizing.

Like this :

$keys = array_map(function($key){ return trim($key); }, array_keys($array));
$array = array_combine($keys, array_values($array));
  • Step 1: trim all keys
  • Step 2: re-associating sanitized keys to values

EDIT

Found out why ... at least if you are using PHP7

In fact if you return an array from a function, this will add null bytes at the end of each array key. See github issue https://github.com/CopernicaMarketingSoftware/PHP-CPP/issues/248 Btw I guess your PHP7 version is old :p keep in mind to update it ;)

Upvotes: 2

Related Questions