In one of my scripts, I try to do the following
$data[] = self::get($row['sr_id']); // <-- line 55
However, PHP does not allow me to do this, giving me this error
Fatal error: Cannot use [] for reading in /file.php on line 55
The self::get function return either a bool, or an object.
Edit: The get function creates a new object which again loads data from a mysql database.
The solution in my case was this:
Bad line:
$this->$ExtraTag[] = $fullscript;
Good line:
$this->{$ExtraTag}[] = $fullscript;
or
$this->ExtraTag[] = $fullscript;
Old PHP versions accepted $var[] in expressions, allowed reading out the $var content regardless of syntax. PHP 5.1 made that illegal. But sometimes the error is triggered outside of the intented context.
So my guess (again: show more code) is that the preceeding line contains an unfinished expression, to which the $data[] joins.
In case of object attribute you can wrap your $data var into { }, but that doesn't seem to be the problem in your case. (Else there is something in line 54, that you didn't show.) The right hand side can't reasonably trigger the error. Even array accessing [] an integer or object wouldn't trigger that fatal error.
So if nothing helps, just use array_push(). Work around PHP.
The error I got was:
Fatal error: Cannot use [] for reading in
/pathtosite/drupal/sites/all/themes/zenui/templates/page.tpl.php on line 33
Sometime the problem is when you include a line like this:
$page['sidebar_first'][]
This might happen if you are copying a variable name and forgot to comment out the line.
There was two problems:
1. Missing semicolon
2. $variable[] must set a variable
After fixing these two problems my code read:
$page['sidebar_first'][] = $value;
Don't forget to comment out line you are not using to help with the debugging process
Hope this helps fellow programmers like me!
I had same error with following:
echo implode(',', $array[]);
which should have been
echo implode(',', $array);
Hope this can help someone
try:
$data = Array();
$data[] = self::get($row['sr_id']); // <-- line 55
I had the same problem with my script, the following line threw the same error:
$array[]=$value
I simply replaced it by
$array[count($array)-1]=$value
and it worked perfectly.
Another possible problem could be an accidental double ==.
For example accidentally doing $myArray[] == $myNewValue; would cause this error (because you are trying to read a value with the == instead of telling PHP to assign a new array index).
Related
I'm working on an existing code base and got back an object with an attribute that starts with a number, which I can see if I call print_r on the object.
Let's say it's $Beeblebrox->2ndhead. When I try to access it like that, I get an error:
Parse error: syntax error, unexpected T_LNUMBER, expecting T_STRING or T_VARIABLE or '{' or '$'
How can I get that attribute?
What about this :
$Beeblebrox->{'2ndhead'}
Actually, you can do this for pretty much any kind of variable -- even for ones that are not class properties.
For example, you could think about a variable's name that contains spaces ; the following syntax will work :
${"My test var"} = 10;
echo ${"My test var"};
Even if, obviously, you would not be able to do anything like this :
$My test var = 10;
echo $My test var;
No idea how it's working internally, though... And after a bit of searching, I cannot find anything about this in the PHP manual.
Only thing I can find about {} and variables is in here : Variable parsing -- but not quite related to the current subject...
But here's an article that shows a couple of other possiblities, and goes farther than the examples I posted here : PHP Variable Names: Curly Brace Madness
And here's another one that gives some additionnal informations about the way those are parsed : PHP grammar notes
I actually found out the answer from a coworker before I asked this, but couldn't find it on Google, so I wanted to post it here in case others have the same problem.
I can access that attribute like so:
$Beeblebrox->{'2ndhead'}
It's not really legal to have an attribute or variable that begins with a number, but somehow a dynamic reference like this makes it possible. Seems like a weird loophole in the language to me.
You can do something like this too:
$aux = '2ndhead';
$Beeblebrox->$aux;
We have an old version of CakePHP that we've moved to a new server running PHP 5.6 and we've started to recieve this error when adding a product to the basket:
Warning (2): Illegal string offset 'AddBasketData'
[APP/controllers/personalisation_controller.php, line 848]
Here is line 848 within the file:
if (is_array($this->data['AddBasketData'])) {
$personalisation_data['Personalise'] = $this->data['AddBasketData'];
}else {
$personalisation_data['Personalise'] = array();
}
Could anyone shed any light on this, I think it's down to the specific PHP version we're running now but any help would be great.
Thanks
Transforming my comments into an answer :
The problem here seems to be that $this->data is a string and not an array.
You should test this first, then check if the offset AddBasketData exists, and finally if the offset AddBasketData is an array :
if (is_array($this->data) && isset($this->data['AddBasketData']) && is_array($this->data['AddBasketData'])) {
$personalisation_data['Personalise'] = $this->data['AddBasketData'];
} else {
$personalisation_data['Personalise'] = array();
}
Of course, that will only correct the symptoms (which is the raised warning), you might have some code debugging to do to find out why $this->data is a string instead of an array.
As noted by #roberto06 in the comments to your question, the reason you're getting the error is because you're trying to treat a string value as an array.
The reason for that specific error message is because you can use the array-offset notation to fetch a single character from the string. Just like you'd do in C's string arrays. But this only support numerical indices, and not a string index as shown in the code you posted.
Now, the easy way to stop the error from occurring is to simply test the type of the data, and whether or not the given index actually exists.Like so:
if (is_array ($this->data) && !empty ($this->data['AddBasketData'])) {
$personalisation_data['Personalise'] = $this->data['AddBasketData'];
} else {
$personalisation_data['Personalise'] = array();
}
However, seeing as you're not suddenly getting this error after update hints towards something else being the issue. Especially since the code you posted expects the value stored in the Personalise index to be an array. I'd trace where the $this->data member gets set, and changed, to see if you can find the underlying reason for why this apparent change in behavior. This might be the side-effect of a more nefarious subtle bug, after all.
Can anyone tell me, if there is an error in the following code, please?
eval ("\$typeselectbit = \"".$cmstpl->get("admin_selectbitdefault")."\";");
$result = $cmsdb->query("SELECT * FROM cms".$n."_type WHERE deleted = '0' ORDER BY typename ASC");
while ($type = $cmsdb->fetch_array($result))
{
$typeid = $type['typeid'];
$typename = $type['typename'];
eval("\$typeselectbit .= \"".$cmstpl->get(ifelse($GPC['typeid'] == $typeid, "typeselectbit2", "typeselectbit"))."\";");
}
It doesn't output the first entry from the array. But maybe the error is somewhere else.
At the moment, I'm not sure, where this problem is coming from.
What do you think? Does it look correct to you?
And if not, what do I have to fix and how exactly should it look like?
Or do I have to look somewhere else in the script?
Any specific hints, which could help to find the reason?
Thank you for your help! :)
The last line in your code eval("\$typeselectbit .= \"".$cmstpl->get(ifelse($GPC['typeid'] == $typeid, "typeselectbit2", "typeselectbit"))."\";"); has a parse error. ifelse is not valid PHP syntax (unless that is a function you have declared previously). It could also be any other number of errors occurring inside of the eval construct.
According to the manual
If there is a parse error in the evaluated code, eval() returns FALSE and execution of the following code continues normally. It is not possible to catch a parse error in eval() using set_error_handler().
It's not clear why you chose to use eval at all here, but one of the down sides, among others, is that you typically can't easily debug these kinds of errors inside of eval. If you ran this code outside of eval you'd immediately see the parse error.
I was trying to use the $$ syntax in PHP for accessing arrays where we can put name of a variable inside another variable and access that variable.
I have used this syntax many times before in different ways, but to my surprise this didn't work for me and lost lot of time over it.
Here is sample code to replicate my problem:
$test=array(
'a'=>array(array(1,2,3),array(4,5,6),array(7,8,9))
);
$var = 'test';
var_dump($$var);
var_dump($$var['a']);
The line var_dump($$var) works as expected, but I'm getting a Warning: Illegal string offset 'a' at line var_dump($$var['a']); and the var_dump prints just null
Why doesn't this work? What am I doing wrong here?
Is there any work around if the syntax is not supported for arrays?
Your $$var['a'] is equivalent to ${$var['a']}. Not ${$var}['a']. The latter being the workaround syntax you are looking for.
Quoting the PHP Manual on Variable Variables:
In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.
See http://codepad.org/lR7QJygX
I am using XAMPP 1.7.2 (PHP 5.3) to devlope on winxp localhost.
There is a function works quite well. Comes from CodeIgniter Module.
function get_cal_eventTitle($year, $month){
$this->db->where('eventYear =', $year);
$this->db->where('eventMonth =', $month);
$this->db->select('eventTitle');
$query = $this->db->get('tb_event_calendar');
$result = $query->result();
foreach ($result as $row)
{
$withEmptyTitle = $row->eventTitle;
//echo $withEmptyTitle.'<br>';
$noEmptyTitle = str_replace(" ","%20",$withEmptyTitle);
$withUrlTitle = '<a href='.base_url().'index.php/calendar/singleEvent/'.$year.'/'.$month.'/'.$noEmptyTitle.'/'.'>'.$withEmptyTitle.'</a>';
//echo $withUrlTitle.'<br>';
$row->eventTitle = $withUrlTitle;
}
return $result;
}
When I upload my code to remote server(PHP 5.2.9). It show error as this,
withEmptyTitle undefined variable
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: withUrlTitle
Filename: models/calendar_model.php
Line Number: 54 // $withEmptyTitle = $row->eventTitle;
But When I enable the comment for the line echo $withEmptyTitle.'<br>';. It works well on remote server.
Assuming withEmptyTitle echo to Apr running event here.
I don't know why? Could you give me some suggestion to fix this issue? Appreciated for your input.
What you're seeing is probably not an error, but a warning.
PHP may be throwing the warning because you're using a variable that hasn't been initialised. It sounds likely that your local development PHP installation has warning messages supressed, whereas your live server has them enabled. (In fact, best practice would be to have it the other way round!)
In this case, it's possible that $withEmptyTitle = $row->eventTitle; is not initialising the $withEmptyTitle variable, if the eventTitle property is returning as unset. It would then fall following line and throw the warning when you try to use the variable in the str_replace() call.
You could avoid this warning by:
Switching warning message off in the PHP.ini
Doing ini_set() to switch it off during the program.
using isset($withEmptyTitle) to check that the variable is set prior to actually using it.
Ensuring that $row does actually contain an eventTitle property (in the context of your program, if it's missing, it may imply bad data or incorrect database table setup? In any case, you could change the SQL query to use IFNULL() or at least ensure the field is explicitly queried.
[EDIT]
I see you've edited the question. In particular, I note the following:
Line Number: 54 // $withEmptyTitle = $row->eventTitle;
I note the // .... does that imply that the line is commented out?? Have you somehow got a copy on the server which has that line commented? That would certainly explain the fact that you're getting warnings!