PHP -- $$array[] = $somthing; — Cannot use [] for reading error [duplicate] - php

This question already has answers here:
Using braces with dynamic variable names in PHP
(9 answers)
Closed 2 years ago.
I'm working on someone else's PHP code and my IDE (PHPstorm) is flagging this line with the error Cannot use [] for reading. The code works fine, but I'm trying to understand why with my limited PHP skills. I've seen double dollar signs in other files and with no error.
$somevar = ($test_me) ? "some-class" : "some-other-class";
$$somevar[] = $some_value; // $somevar[] is flagged

This is not the answer to your problem but what me and most other think you should do.
Switch to an array, that way you have one variable with everything that is variable in it.
You can loop the array to find what you need and you don't allocate variable names that may conflict with other variables.
$some_value =1;
$test_me = true;
$somevar = ($test_me) ? "some-class" : "some-other-class";
$arr[$somevar] = $some_value;
var_dump($arr);
This results in an associative array with the key "some-class" and value 1.

Use curly brackets { } for interpolation :
$somevar = "some-other-class";
${$somevar}[] = "foo";
var_dump(${$somevar});
Output :
array(1) {
[0] => string(3) "foo"
}

Related

Best practice: how to increment not existing element of array [duplicate]

This question already has answers here:
Notice: Undefined index when trying to increment an associative array in PHP
(6 answers)
Closed 4 months ago.
I want to increment a value of an array, which is potentially not existing yet.
$array = [];
$array['nonExistentYet']++; // Notice
Problem
This leads to a NOTICE.
Attempt
I found a way to do this, but its kinda clunky:
$array = [];
$array['nonExistentYet'] = ($array['nonExistentYet'] ?? 0) + 1;
Question
Is there a more human readable/elegant way to do this?
well i guess a more readable way would be to use if..else as,
$arr = [];
if(array_key_exists('nonExistentYet', $arr)) {
$arr['nonExistentYet'] += 1;
}
else {
$arr['nonExistentYet'] = 1;
}
If this is used often, you can define a little helper method, which also uses an interesting side effect...
function inc(&$element) {
$element++;
}
$array = [];
inc($array['nonExistentYet']);
print_r($array);
gives...
Array
(
[nonExistentYet] => 1
)
with no warning.
As you can see the function defines the parameter as &$element, if this value doesn't exist, then it will be created, so the function call itself will create the element and then it will just increment it.
My standard implementation for this is:
if (isset($array['nonExistentYet']))
$array['nonExistentYet']++;
else
$array['nonExistentYet'] = 1;
But this is one of the rarely scenarios where I use the # operator to suppress warnings, but only if I have full control over the array:
#$array['nonExistentYet']++;
Generally, it is not good to suppress warnings or error messages!
What you ask is a little vague,
Either the variable exists and you increment it, or it does not exist in this case you create it.
In another case suppose that you want to do it in a for loop, in this case you do not have to worry about the existence of the variable.
One way is ternary operator, which checks if array value exists:
$array['iDoNotExistYet'] = empty($array['iDoNotExistYet']) ? 1 : ++$array['iDoNotExistYet'];
Other one would be just rewriting it to if and else condition.

PHP - auto assign a different name to a variable of variable [duplicate]

This question already has answers here:
Using braces with dynamic variable names in PHP
(9 answers)
Closed 6 years ago.
Using PHP variable variables with mysqli_fetch_assoc to auto-format variables like $column_name="some_value" (code below):
while ($account_row=mysqli_fetch_assoc($account_results))
{
foreach ($account_row as $key=>$value)
{
$$key=trim(stripslashes($value));
}
}
So if I have a column "username" and row value "someuser", this code creates:
$username="someuser";
However, in some cases I need variable names to be DIFFERENT from column names. For example, I need code to create:
$username_temp="someuser";
How could I do that? Using this code gives an error:
$$key."_temp"=trim(stripslashes($value));
No other ideas in my head.
change $$key."_temp" to ${$key."_temp"} have a look on below solution:
$value = 'test';
$key="someuser";
${$key."_temp"}=$value;
echo $someuser_temp; //output test
Please try this ${$key . "_temp"} = trim(stripslashes($value));

Get json object's value in php if its name contains dots in PHP [duplicate]

This question already has answers here:
php object attribute with dot in name
(5 answers)
Closed 7 years ago.
I have a json like the following
{"root":{
"version":"1",
"lastAlarmID":"123",
"proUser":"1",
"password":"asd123##",
"syncDate":"22-12-2014",
"hello.world":"something"
}
}
After json_decode(), I can get all the values except that of the last one hello.world, since it contain a dot.
$obj->root->hello.world doesn't work. I got solutions for doing it in Javascript but I want a solution in php.
$obj->root->{'hello.world'} will work.
ps: $obj->root->{hello.world} might not work.
b.t.w: Why not use Array? json_decode($json, true) will return Array. Then $a['root']['hello.world'] will always work.
You have two options here:
First option: convert the object to an array, and either access the properties that way, or convert the name to a safe one:
<?php
$array = (array) $obj;
// access the value here
$value = $array['hello.world'];
// assign a safe refernce
$array[hello_world] = &$array['hello.world'];
Second option: use quotes and brakets:
<?php
$value = $obj->root->{'hello.world'};
This is working
echo $test->root->{'hello.world'};
Check example
<?php
$Data='{"root":{
"version":"1",
"lastAlarmID":"123",
"proUser":"1",
"password":"asd123##",
"syncDate":"22-12-2014",
"hello.world":"something"}
}';
$test=json_decode($Data);
print_r($test);
echo $test->root->{'hello.world'};
?>
Output
something
You can use variable variables (http://php.net/manual/en/language.variables.variable.php):
$a = 'hello.world';
$obj->root->$a;

Assigning value to dynamic object's property [duplicate]

This question already has answers here:
How do I dynamically write a PHP object property name?
(5 answers)
Closed 7 years ago.
This is not only tricky to explain, but tricky to do:
I'm trying to access and replace
$myObject->customField[0] = "some value";
but if I do
$str = "customField";
$myObject->$str[0] = "some value";
That doesn't work and if I do
$str = "customField";
$obj = $myObject->$str;
$obj[0];
That won't work either. I can change the values if I don't do this dynamically but I'm having to loop through a lot so doing it dynamic will be very helpful.
EDIT (answer)
Turns out curly braces does the trick. ie
$str = "customField";
$myObject->{$str}[0] = "some value";
Why do you want to have dynamic property names? The best answer is: don't do it this way. Consider using an associative array instead:
$myObject->customFields = array();
$myObject->customFields[$str] = "some value";

php how to access object properties with hyphen? [duplicate]

This question already has answers here:
How do I access this object property with an illegal name?
(2 answers)
Closed 9 years ago.
The json format.
{
"message-count":"1",
"messages":[
{
"status":"returnCode",
"error-text":"error-message"
}
]
}
In php, I successfully get "status" value with $response->messages[0]->status
But when I wanted to access "error-text" properties, the code $response->messages[0]->error-text gives me error.
How to access object properties with hyphen?
here is the way!
$object->{"message-count"};
$response->messages[0]->{'error-text'};
hope this helps
any string (bytes sequence) can be used as a class field
$object->{"123"} = 10; // numbers
$object->{"{a}"} = 10; // special characters
$object->{"òòèè"} = 10; // non ascii characters
Use the {} syntax:
echo $response->messages[0]->{'error-text'};
Please, use standard PHP feature - accessing variables within curly braces:
class t {}
$a = new t();
$a->{"o-o"} = 1;
echo $a->{"o-o"};
So, you need to write $response->messages[0]->{"error-text"}.

Categories