Illegal string offset when printing array values in PHP - php

Looked at many similiar problems and the solutions didn't help me. I'm getting a strange error message Warning: Illegal string offset 'officeName' in... and the var_dump of the variable generating the error looks like this:
array(10) {
["officeId"]=>
string(5) "11237"
["officeName"]=>
string(37) "Pro Office Inc."
}
The code that produces the errors is:
foreach($objects as $key => $value){
var_dump($value);
}
So $value is an array. What's wrong with what I'm doing and how can I fix it?

Make a double check of every value from the array, since one of these items may be an array, but there may be others which are not. In such cases it is always better to var_dump() the whole $objects array instead of each item, since it's easier to spot any error.
Besides, the Illegal string offset error usually hints that you're trying to treat a string as an array and/or access it's keys, which don't exist.

Related

Undefined offset in array - But I know it's in there

I have an array (or associative array), with keys and values.
Then, when trying to read one of the keys, which IS in the array, I get an "undefined offset" notice.
I have two examples where it happened. One was "exploding" a string like "AAA|BBB|CCC", using | as the separator, then trying to read the resulting array at position 1.
var_dump() correctly shows an array having offsets 0 to 2, with the correct values. But I still get the notice.
Another example is I get an array (from an AJAX call, I json_decode it, etc), then I typed the following code:
foreach (array_keys($myDecodedArray) as $k) {
$value = $myDecodedArray[$k];
someOtherCode();
}
I had that damn notice appear when trying to read $myDecodedArray[$k], although php itself had just told me the key existed !
So, I solved that last case by going
foreach ($myDecodedArray as $k => $value) {
someOtherCode();
}
but still, this is extremely annoying, and makes no sense to me.
Any of you run into that problem before?
Do you have any information about what could cause that?
[EDIT]
Rahul Meshram's suggestion (which I upvoted in the comments) solved my second problem case.
However, the first case still happens (exploding a string into an array, then trying to access that array's values by their numeric keys).
The keys ARE numeric (gettype returns 'integer', var_dump on that key shows an integer too, with the right value), but trying to access $explodedArray[1] still results in that notice being displayed, despite $explodedArray having keys 0, 1, and 2, with associated values.

PHP Illegal string offset

I have a problem with this code :
echo $f[0]['id']; // result 19275
But after the error message is :
Illegal string offset 'id'
Why this error message? Offset 'id' exists and has a value
The reason you would see this error message is because $f[0] returns a string, not a sub array. A var_dump should return the proper answer to your problem. Once your question is updated with the result of that var_dump, I can help you further (print_r will also work)
For example, you could have the following structure
array(
'19275'
)
This satisfies your requirement above, and is what you are most likely being returned.
However, you're assuming the following
array(
array('id' => '19275')
)
You are expecting an associative array, when you are merely dealing with a simple numerically indexed array.

array_diff gives Array to String conversion error in drupal

I am experiencing a weird error from an array_diff statement. The statement is:
$query = array_diff($params, array('f' => array()));
and the var_dump of the $params is array(1) { ["f"]=> array(0) { } }
This happens in a drupal module called Islandora_solr_search and I get the following error message twice like below
Notice: Array to string conversion in IslandoraSolrResults->setBreadcrumbs() (line 427 of /var/www/drupal/sites/all/modules/islandora_solr_search/includes/results.inc).
Notice: Array to string conversion in IslandoraSolrResults->setBreadcrumbs() (line 427 of /var/www/drupal/sites/all/modules/islandora_solr_search/includes/results.inc).
Does anyone know why this happens?
array_diff throws notice errors when it finds an array inside an array. See the comment by Michiel Thalen
I may assume that you're running php 5.4 or higher. You can see it by yourself, by checking your array_diff statement in the sandbox (you can switch php versions there)
There's also a discussion in Drupal forums
As a quickfix I suggest this:
$query = #array_diff($params, array('f' => array()));
And in case you're going to use array_diff function with deep arrays, there are plenty
of solutions on the net, including official php.net resource.

in_array() works fine but throws error?

AFAIK - in_array() should return TRUE or FALSE.
In my case, It does validate as true - but still throwing an error:
[function.in-array]: Wrong datatype for second argument
The line is this :
in_array($key,$instance['cfl2']);
and the $instance['cfl2'] is a verified array which looks like this :
array(2) { [0]=> string(8) "price" [1]=> string(6) "age" }
My questions are :
What am I doing wrong.
Why it is throwing an error (but still working fine and returns true)
Is the problem occur because I use some kind of nested array ? (meaning that an array item $instance['cfl2'] is actually an array by itself ?
I also tried $is = $instance['cfl2'] and in_array($key,$is) - but the result was the same error.
You can cast a variable to an array to avoid this error:
in_array($key, (array) $instance['cfl2'])
in_array() will deal as in_array("search", $instance).
If you are using a nested or multidiamentional array, then in_array() wont work and you should write a separate function to handle this. Or use array_key_exists() instead. It will work for certain specific situations. Find out if your requirement is met.
ie
if(array_key_exists($key,$instance['cfl2']))

Associative array with 2 names that are the same?

I'm working on a PHP script that updates some tracking numbers based on an uploaded CSV file. The import worked fine for some time, then the exports started having quotation marks around the values. I thought this would be fine, but it started rejecting the files. Doing some debugging and var_dumps, I discovered a very strange situation I have never seen before - An associative array with two indices with the same name. I ran the code setting the fields (shown below) and added a line:
$v['order_id'] = '119205';
After running that line, the var_dump was as follows:
array(15) {
["order_id"]=>
string(6) "119205"
["Tracking Number"]=>
string(22) "6735675476254654756"
["Postage"]=>
string(4) "1.64"
["order_id"]=>
string(6) "119205"
}
Some fields removed for brevity. As you can see, there are two ["order_id"] indices. How is this even possible?
Here is the code that sets the values of the array dumped above:
$v = array();
foreach ($map as $k => $n) {
$v[$n] = #$data[$k];
}
with $map being the CSV header row. Trying to reference $v['order_id'] without running the $v['order_id'] = '119205'; line resulted in this error:
Notice: Undefined index: order_id in /dir/to/php/file/php_file.php</b> on line 29
Manually setting the index worked as expected, pulling the rest of the data from $v without issue.
EDIT:
Dumping the array_keys resulted in:
[0]=>
string(11) "order_id"
and:
[14]=>
string(8) "order_id"
making the first one three characters longer.
var_export still resulted in identical indices.
How can I get rid of these invisible characters? I've already tried $v[trim($n)] = #$data[$k]; in the foreach().
Try var_dump(array_keys($v)). Find the key that looks like order_id and make sure the string's length is exactly 8. I suspect there may be a NUL character in there, which would give it a length of 9 and cause it to not respond to order_id.
Quote:
In the output of var_dump(), the null bytes are not visible.
Technically you can not have two times the same key in PHP in an array. It might be that var_dump is not giving the right keys here (e.g. probably some null-chars or other non-displayable chars are dropped).
Instead you might want to check, what's going on:
var_dump(array_keys($data));
Maybe it helps, the following is a related question which demonstrates when var_dump hides some information:
Array to Object and Object to Array in PHP - interesting behaviour

Categories