PHP: Array to string conversion - php

We're running PHP 5.3.10-1ubuntu3.15 with Suhosin-Patch, and I just ran across the weirdest thing. I keep getting an Array to string conversion error.
Here is some code with line numbers:
115 $report['report'][$key]['report'] = array();
116 watchdog('ranking_report_field', 'key is a: ' . gettype($key), array(), WATCHDOG_NOTICE);
117 $report['report'][$key]['report'] = array(
'#markup' => "<p>No information available.</p><p>For questions, <a href='mailto:$emailAddr'>email</a> your account executive ($emailAddr).</p>",
);
Here are Drupal's (sequential) logs for those line numbers:
Notice: Array to string conversion in foo() (line 115 of /var/www/...
key is a: string
Notice: Array to string conversion in foo() (line 117 of /var/www/...
So far as I can tell there's no array to string conversion that should be taking place. Someone help me out with a second pair of eyes, please - or is this some kind of bug that just hit PHP?

One of the array keys is mapped to a string not an array. Here is a program for how such an error could occur.
<?php
$key = 0;
$report = array();
$report['report'] = array();
$report['report'][$key] = 'report';
// Array to string conversion error
$report['report'][$key]['report'] = array();
// what I assume you are expecting is
$report['report'][$key] = array();
$report['report'][$key]['report'] = array(); // no more notices
NOTE: at his time the OP has not included info for how the array is created

Related

PHP array to string conversion notice with CachingIterator

I have done some searching on Stackoverflow already on this topic, however as far as I can tell, I am not treating an array as a string ?
The message I am getting is :
Array to string conversion in X on line 42
Line 42 of my code is the opening of a foreach loop :
foreach ($collection as $element) {
Variable $collection is a caching iterator that is based on database output:
$collection=new \CachingIterator(new \ArrayIterator($this->dbData));
If I print_r() on $this->dbData, I certainly get an array:
Array
(
[0] => Array
(
[c_id] => A
)
[1] => Array
(
[c_id] => B
)
So, in summary:
We have a confirmed output of an array
We know that ArrayIterator() expects an array as argument
We know that CachingIterator() expects an Iterator as argument
We know that foreach() can loop over an Iterator
TL;DR I am really not sure what I am treating as string here ?
EDIT TO ADD....
Even if I greatly simplify my code, I can still reproduce:
<?php
error_reporting (E_ALL | E_STRICT);
ini_set ('display_errors', 1);
$arrX=array(array("c_id"=>"A"),array("c_id"=>"B"));
$collection=new \CachingIterator(new \ArrayIterator($arrX));
foreach($collection as $element) {
echo $element["c_id"].PHP_EOL;
}
Notice: Array to string conversion in /Users/bp/tmp/test.php on line 6
A
Notice: Array to string conversion in /Users/bp/tmp/test.php on line 6
B
The short answer is, you're inadvertently asking the CachingIterator to convert the sub-arrays to strings during iteration. To not do this, don't use the CachingIterator::CALL_TOSTRING or CachingIterator::TOSTRING_USE_INNER flags.
You can set no flags, by using 0 as the value for the $flags parameter, or use a different flag: this can be done in the constructor, or after initialisation by using CachingIterator::setFlags().
For example:
$array = [["c_id" => "A"], ["c_id" => "B"]];
$collection = new CachingIterator(new ArrayIterator($array), 0);
foreach ($collection as $element) {
// no E_NOTICE messages, yay!
}
And a few words by way of explanation...
By default, the CachingIterator class sets the CachingIterator::CALL_TOSTRING flag as noted in the PHP manual page on CachingIterator.
public __construct ( Iterator $iterator [, int $flags = self::CALL_TOSTRING ] )
When this flag (or the CachingIterator::TOSTRING_USE_INNER flag) is set, and the CachingIterator::next() method is called (i.e. during iteration) the current value (in this case each sub-array) or the inner iterator (in this case, the ArrayIterator), respectively, is converted to a string and saved internally. This string value is what is returned from CachingIterator::__toString() when one of those flags is used.
When using any of the other flags, the above is not done when calling CachingIterator::next().
You need CachingIterator::FULL_CACHE per this PHP docs comment
<?php
$arrX = array(
array( "c_id" => "A" ),
array( "c_id" => "B" )
);
$collection = new \CachingIterator( new \ArrayIterator( $arrX ), CachingIterator::FULL_CACHE );
foreach( $collection as $element )
{
echo $element["c_id"].PHP_EOL;
}

How to work (create and access) empty 2D array in PHP [duplicate]

This question already has answers here:
How to solve PHP error 'Notice: Array to string conversion in...'
(6 answers)
Closed 5 years ago.
I want to define in PHP a new 2D array (to fill and access it later in cycle) but I have problem to deal with it. I went through some articles (e.g. here), but it still does not work for me.
My code is:
$part = array(array());
for ($i=0; $i<4; $i++) {
for ($j=0; $j<3; $j++) {
$part[$i][$j]=3;
}
}
for ($i=0; $i<4; $i++) {
for ($j=0; $j<3; $j++) {
echo "values i=$i, j=$j: $part[$i][$j]\n<br>";
}
}
Result of code above is:
Notice: Array to string conversion in /var/www/html/ftth1/sandbox.php on line 43
values i=0, j=0: Array[0]
Notice: Array to string conversion in /var/www/html/ftth1/sandbox.php on line 43
values i=0, j=1: Array[1]
Notice: Array to string conversion in /var/www/html/ftth1/sandbox.php on line 43
values i=0, j=2: Array[2]
Notice: Array to string conversion in /var/www/html/ftth1/sandbox.php on line 43
values i=1, j=0: Array[0]
...
Line 43 mentioned in output is:
echo "values i=$i, j=$j: $part[$i][$j]\n<br>";
I have tried to use also just a little bit modified version of code from above mentioned article, however result was same:
Code:
$a = array(); // array of columns
for($c=0; $c<5; $c++){
$a[$c] = array(); // array of cells for column $c
for($r=0; $r<3; $r++){
$a[$c][$r] = rand();
echo "$a[$c][$r] \n<br>";
}
}
Result:
Notice: Array to string conversion in /var/www/html/ftth1/sandbox.php on line 55
Array[0]
Notice: Array to string conversion in /var/www/html/ftth1/sandbox.php on line 55
Array[1]
Notice: Array to string conversion in /var/www/html/ftth1/sandbox.php on line 55
Array[2]
Notice: Array to string conversion in /var/www/html/ftth1/sandbox.php on line 55
Array[0]
...
Line 55 mentioned above is:
echo "$a[$c][$r] \n<br>";
Could someone help me with this problem? Thanks.
You need to use braces in you use a "complex" expression in the string interpolation, i.e.
echo "values i=$i, j=$j: {$part[$i][$j]}\n<br>";
Note the { ... } around the $part[$i][$j] part.
An expression becomes "complex" as soon as it's more than a plain variable name.
See PHP manual on simple string interpolation syntax
and complex syntax.
Note that the complex syntax can be used for plain variables as well, i.e. you could use {$i} ... {$j} for consistency.

Php Dynamic Variable

$X['high'] = 1234;
$var = array("X","high");
This is working:
$temp = $$var[0];
$temp = $temp[$var[1]];
echo $temp;
But this isn't working:
echo $$var[0][$var[1]];
Why? How can i make it works?
You should explain to php parser how you want this statement to be parsed:
echo ${$var[0]}[$var[1]];
Without brackets you will have:
php7
Notice: Array to string conversion in /in/cvZqc on line 5
Notice: Undefined variable: Array in /in/cvZqc on line 5
php5
Warning: Illegal string offset 'high' in /in/cvZqc on line 5
Notice: Array to string conversion in /in/cvZqc on line 5
Sample link.

Notice: Undefined offset: 0 using Array in [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 9 years ago.
Not sure how to fix this error
Notice: Undefined offset: 0 in C:\xampp\htdocs\streams.php on line 50
Notice: Undefined offset: 0 in C:\xampp\htdocs\streams.php on line 53
Notice: Undefined offset: 0 in C:\xampp\htdocs\streams.php on line 54
Code its referring to:
<?php
$members = array("hawkmyg");
$userGrab = "http://api.justin.tv/api/stream/list.json?channel=";
$checkedOnline = array ();
foreach($members as $i =>$value){
$userGrab .= ",";
$userGrab .= $value;
}
unset($value);
//grabs the channel data from twitch.tv streams
$json_file = file_get_contents($userGrab, 0, null, null);
$json_array = json_decode($json_file, true);
//get's member names from stream url's and checks for online members
foreach($members as $i =>$value){
$title = $json_array[$i]['channel']['channel_url'];
$array = explode('/', $title);
$member = end($array);
$viewer = $json_array[$i] ['stream_count'];
onlinecheck($member, $viewer);
$checkedOnline[] = signin($member);
}
Cannot figure out how to fix
The notice of an undefined offset occurs when one calls an array element with the specific index, for example, echo $array[$index], but the index is not defined within the array.
In your code, the array $members has one element (with index 0). So we're walking exactly one time through your foreach loop.
You're calling $json_array[$i]['channel']['channel_url'] where $i = 0, but $json_array[0] does not exist.
You should check the contents of $json_array using print_r() or var_dump().
I tested the script myself, and when I read the contents of the link http://api.justin.tv/api/stream/list.json?channel=,hawkmyg, it returned an empty JSON array. The channel 'hawkmyg' does not exist.
I tried the channel 'hatoyatv', and it just worked.

Error encountered when getting values from array with sting values

I am using the following array:
$words = $xpath->query('//div[#id="relatedSearches"]/a');
$related_words=array();
foreach ($words as $word) {
$related_words[]=trim($word->nodeValue);
}
var_dump($related_words); // to debug
and the output is:
array
0 => string 'internet books' (length=14)
1 => string 'internet business' (length=17)
2 => string 'internet marketing' (length=18)
and in my code, at a later stage, I use the following code segment to assign values to another array:
$values = array_values($related_words);
Everything is okay, if the output of $related_words does not contain spaces e.g
<li>internet <li>book <li>business
Whenever a space is encountered in input array $related_words I get the error:
Catchable fatal error: Object of class DOMElement could not be converted to string in line 22
Line 22 is $values = array_values($input);
Anyone can please give me a solution to this? Or help?
I searched the same error on stackoverflow but failed to get help..

Categories