I've got an odd error in my PHP code regarding dynamic arrays.
The error outputted is:
Fatal error: Cannot use string offset as an array ... on line 89
This is a portion of my code, it is within a foreach loop, which is looping through settings in a database:
foreach($query->fetchAll() as $row)
{
if($site!=CURRENT_SITE_TEMPLATE)
{
$property = 'foreignSettings';
$propertyType = 'foreignSettingsTypes';
} else {
$property = 'settings';
$propertyType = 'settingTypes';
}
$this->$property[$row['variable_section']][$row['variable_name']] = $row['variable_value'];
settype($this->$property[$row['variable_section']][$row['variable_name']],$row['variable_type']);
$this->$propertyType[$row['variable_section']][$row['variable_name']] = $row['variable_type'];
}
For the sake of the example code, $site is 'admin' and CURRENT_SITE_TEMPLATE is 'admin'.
In addition, $foreignSettings, $foreignSettingsTypes, $settings, and $settingTypes are all defined as arrays in the class scope
The error is on line 89, which is:
$this->$property[$row['variable_section']][$row['variable_name']] = $row['variable_value'];
I originally thought it was because of the $property variable accesing the array, however, this looks like valid legal code in the PHP documentation ( http://php.net/manual/en/language.variables.variable.php in example #1)
Any help on this error would be appreciated.
Thanks
In your given example $property is a string. You are then trying to use that as an array. Strings only has numeric indexes (if you need to use as an array).
The problem is as follows: $this->$property[0] means you access the 0th place of $property which in your case would be the first letter of the string $property. Thus you end up with $this->f or $this->s.
with $this->$property[0][0] you would be trying to access the 0th place of the 0th place of the $property string what results in an error because you try to access the 0th place of the char s what is not possible since the char s can not be referenced as an array.
what you want is $this->{$propperty}[0][0] what means that you try to access the 0th place of the 0th place of the variable that has the name $propperty.
Related
I have a very strange problem.
I am running through a foreach loop to compile an array but I receive an error.
I reveive the following warning :
Warning: Illegal string offset 'clientaccount_id' in
For this line of code:
$this->PreparedData[$table][$field] = 0;
I would say this to be logic if I would be doing something like:
$testVariable = $this->PreparedData[$table][$field];
Then the variable $field filled with 'clientaccount_id' would not exist.
But I am CREATING the field 'clientaccount_id' so to ME this is almost impossible to give an error.
The code
private function AssignData(){
foreach($this->FieldKeys as $table => $value){
///######## IF THE PREPARED DATA ARRAY DOES NOT EXIST
if(isset($this->PreparedData[$table]) === false){
///######## SET THE ARRAY KEY
$this->PreparedData[$table] = array();
}
///######## RUN THROUGH ALL SET SUB DATA
foreach($value as $field){
///######## IF THE FIELD EXISTS
if(isset($this->AccountData[$field]) === true){
///######## ASSIGN THE DATA
///$this->PreparedData[$table][$field] = $this->AccountData[$field];
///$this->PreparedData[$field] = $this->AccountData[$field];
$this->PreparedData[$table][$field] = 0;
}
}
}
exit('GOT THROUGH!!');
}
Could anyone see the error I am overlooking?
Solved!!
Thanks to VMcreator
Changed :
isset($this->PreparedData[$table]) === false
to this:
is_array($this->PreparedData[$table]) === false
Please read the explanation below WHY
Try to change this line:
isset($this->PreparedData[$table]) === false
to this:
!is_array($this->PreparedData[$table])
I saw this explanation here:
It just boils down to PHP's crazy type system.
$fruits['response']['errormessage'] is the string 'banana', so you're
attempting to access a character in that string by the ['orange']
index.
The string 'orange' is converted to an integer for the purposes of
indexing, so it becomes 0, as in
$fruits['response']['errormessage'][0]. The 0th index of a string is
the first character of the string, so for non-empty strings it's
essentially set. Thus isset() returns true.
You might be curious why your situation is comparable to that quoted statement even if $this->PreparedData[$table] seems a single dimensional array only, well its not a single dimensional array only, because you are accessing a class object, its just like doing this $this["PreparedData"][$table].
I'm getting this error:
'( ! ) Warning: Cannot use a scalar value as an array in C:\xampp\htdocs\or2LAST\admin\adminData.php on line 5`
the code for this error (line 5):
$admin['push']=array(
1=>"yes",
2=>"no"
);
i tried to use "1" & "2" for the key but it didn't solve the problem.
where is the problem and why this error occurred?
The problem is with $admin. You need to declare it as an array before using it:
$admin = array();
Whatever it is now, it's not an array. Possibly on a previous line you're overwriting it with some new (scalar) value instead of appending to it.
You need to declace $admin to an array first
like
$admin=array();
then try
$admin['push']=array(
1=>"yes",
2=>"no"
);
Your problem is probably with variable $admin, following should work just fine (assuming $admin is not previously declared).
$admin = array(); //<--!!
$admin['push']=array(
1=>"yes",
2=>"no"
);
There must be an obvious bug in this code but I'm not seeing it. Mind taking a look?
The below code returns
string
fleet
Warning: Illegal offset type (line 6)
The taskforces subroutine just pulls an .ini file, reads it into an array, and returns the array, which the foreach then iterates through. In relevant part, the array looks like this.
; this is an INI file
[scout]
type = "fleet"
Here is the code:
foreach($_SESSION['ini']->taskforces() as $key => $val)
{
echo gettype($val["type"]);
echo $val["type"];
if($val["type"] == "fleet") {
$commanderData[$val] = "BLOB";
$commanderData["sc$val"] = "INT NOT NULL";
}
}
I'd like to not have the illegal offset type, because I want the code to go through to the if condition. What obvious thing am I missing?
Thanks.
Instead of this:
echo $val["type"];
you should have simply:
echo $val;
Just because $val is not an array, it's a string. You've made a foreach through an array, so on each iteration you get an array key and an array value (which is, obviously, the string "fleet").
I'm not sure why this caused the problem, but I realized that the result of the if statement was not correct. The code
$commanderData[$val] = "BLOB";
attempts to use the matrix $val as the key for the $commanderData array. It should use the string $key from the iteration through the ini file. Once fixed, I stopped getting the warning, but it's not clear why this would have thrown the error on the proceeding line.
I am getting the following error from the method presented below:
Notice: Uninitialized string offset: 5 in /path/to/file.php on line 30 Fatal error: Cannot access empty property in path/to/file.php on line 30
private function parse($xml, $index = '') {
echo count($xml->children()); //outputs 6
$count = 0;
foreach ($xml->children() as $key => $value) {
$this->$key[$count] = array();
$count++;
}
}
Any ideas why if I build an multi-dimensional in this way it results in an error?
If I change the assignment to:
$this->$key = array($count = > array());
This simply re-assigns the property each loop.
Thanks
Rich
Imagine you've got a string:
$string = 'abc`;
Doing substring access (which looks like array) will return you the character:
echo $string[2]; # c
Or you get your error when you're out of the index:
echo $string[3]; # null + warning
So now accessing a member of your object $this dynamically:
$this->$string[2]; # access $this->c
However this one breaks hardly:
$this->$string[3]; # access $this->null (not possible)
This gives you your fatal error of an empty property, a property with no name.
This explain what happens in your code, you have not told what you're trying to do so I hope this information will help you to continue with writing your parse function.
You should try to create the array before filling it.
I.e. $this->key = array();
That is, before looping through the XML elements.
Trying to use a class that expects something like:
$client->firstname = 'bob';
$client->lastname = 'jones';
So I want to pass this data to the script in an array... where the keys and values are set elsewhere. I want to step through the array passing the key and value to the class. Trying to use this:
while($Val = current($CreateClientData)){
$client->key($CreateClientData) = $Val;
next($CreateClientData);
}
getting this:
Fatal error: Can't use method return value in write context in
blahblahpath on line 40.
Line 40 being: $client->key($CreateClientData) = $Val;
How can I do this?
If $client is already an instance of some class, and $CreateClientData is an array, then you probably wan to do something like this:
foreach($CreateClientData as $k => $v) {
$client->{$k} = $v;
}
This assumes of course that every key in the array is a valid member of the $client instance. If not, then you will have to do some additional checking before assigning the value, or you will have to wrap the assignment in a try / catch.
EDIT
The answer as to why your code doesn't work is because PHP doesn't allow for assignment of class properties to certain functions that return values. In your case, key($CreateClientData) returns a key. So you could alter your code and just add
$key = key($CreateClientData);
$client->$key = $Val;
But, the foreach loop is a lot cleaner anyway.
Why don't you use a foreach loop?
foreach($CreateClientData as $key => $val) {
$client->$key = $val;
}