PHP - Adding string value to associative array - php

This seem so simple, and yet I can't find a solution anywhere.
What I want to do is add the contents (r-value) of a variable to an associative array instead of a reference to the variable.
For example, I want this:
$myStr1 = "sometext";
$myStr2 = "someothertext";
$myArray = array(
"key1"=>$myStr1,
"key2"=>$myStr2
);
echo($myArray["key1"]);
To produce this:
"sometext"
Instead of this:
"1" // why??
Any help would be appreciated.
EDIT:
The above works; my bad. Here's the real problem - my $myStr1 variable isn't just assiged a string literal like in the above; it's created using the following syntax:
$myStr1 = "sometext" + anObject->intProperty + "moretext";
Basically I use the + to concatenate various types into a string. Maybe + isn't doing what I think it's doing?
EDIT:
It was definitely the + operator. I casted all non-strings to strings and used . to concatenate instead.

You've got it correct the first time. Try this:
$myStr1 = "sometext";
$myStr2 = "someothertext";
$myArray = array(
"key1"=>$myStr1,
"key2"=>$myStr2
);
unset($myStr1);
echo($myArray["key1"]);
Even though we unset() the $myStr1 variable, it still echoed sometext.
It should be noted that while it is possible to set $myStr1 by reference, it's not the default.

Try your code and its result is:
sometext

Related

Access "complex" object attributes from string in PHP

I have an object and need to access an attribute from a string like this:
$string = 'items[0]->sellers[0]->commertialOffer->Price';
I've tried something like this but it doesn't work:
$myObject->{$string};
Any idea?
$items = '{"items":[{"sellers":[{"commertialOffer":{"Price":33}}]}]}';
$myObject = json_decode($items);
$string = 'items[0]->sellers[0]->commertialOffer->Price';
echo ($myObject->{'items'}[0]->{'sellers'}[0]->{'commertialOffer'}->{'Price'});
echo ($myObject->items[0]->sellers[0]->commertialOffer->Price);
As $myObject->items is an array you can`t access it like
$string = 'items[0]';
echo $myObject->{$string};
You can access that by using
$string = 'items';
echo $myObject->{$string}[0];
Are you passing the string between two functions ? If yes , then take 4 values and create the string like :-
$string = $value1.'|'.$value2.'|'.$value3.'|'.$value4 ;
Then explode the string and get back the 4 values .
You probably want to revise your problem because interpreting raw code from a string is often a bad idea. You could potentially use the eval function: see. Again, this is probably not a good idea: when is eval evil?

PHP Value from Array

I'm trying to work out how to get values from one of three arrays based on the array name.
$ABC001 = array('A'=>'10','B'=>'2','C'=>'1.0');
$ABC002 = array('A'=>'20','B'=>'4','C'=>'1.1');
$ABC003 = array('A'=>'30','B'=>'6','C'=>'1.2');
I have a variable passed to my script it will be contain something like ABC#001 or ABC#002
I'm removing the # so the var value now matches the array name/
$test = str_replace('#','',$var);
If I do var_dump ( $$test ) I get all the values from the correct array, but if I do echo $$test['A'] or echo $$test[0] I don't get the value from the first key in the correct array.
Can someone advise how to do this.
Thanks
try this ${$test} to get the values of the array
<?php
$ABC001 = array('A'=>'10','B'=>'2','C'=>'1.0');
$ABC002 = array('A'=>'20','B'=>'4','C'=>'1.1');
$ABC003 = array('A'=>'30','B'=>'6','C'=>'1.2');
$var = "ABC#002";
$test = str_replace('#','',$var);
var_dump(${$test}['A']);
In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$test['A'] then the parser needs to know if you meant to use $test['A'] as a variable, The syntax for resolving this ambiguity is: ${$test}['A'] . Please check the documention here PHP Variable Variable

PHP variable variable name containing index

$arr[0]=123;
$a="arr[0]";
echo $$a;
gives me error
Notice: Undefined variable: arr[0]
on the last line.
What should I do to make it work?
EDIT:
Above is the simplification of what I want to do. If someone wants to know why I want to do this, then here's the explanation:
This is something like what I want to do:
if(condition){
$a=$arr1[0][0];
$b=$arr1[0][1];
$c=$arr1[0][2];
}
else{
$a=$arr2[0];
$b=$arr2[1];
$c=$arr2[2];
}
I can compact it like this:
if(condition)
$arr=$arr1[0];
else
$arr=$arr2;
$a=$arr[0];
$a=$arr[1];
$a=$arr[2];
But I wanted to try doing this using variable variable:
if(condition)
$arr="$arr1[0]";
else
$arr="$arr2";
$a={$$arr}[0];
$b={$$arr}[1];
$c={$$arr}[2];
Sure, we don't need variable variables as we can still code without them. I want to know, for learning PHP, why the code won't work.
Now that you said what you’re actually trying to accomplish: Your code doesn’t work because if you look at $arr1[0][0], only arr is the variable name; the [0] are special accessors for certain types like strings or arrays.
With variable variables you can only specify the name but not any accessor or other operation:
A variable variable takes the value of a variable and treats that as the name of a variable.
Your solution with the additional variable holding the array to access later on would be the best solution to your problem.
What you are trying to do just won't work - the code $arr[0] is referencing a variable called $arr, and then applying the array-access operator ([$key]) to get the element with key 0. There is no variable called $arr[0], so you cannot reference it with variable-variables any more than you could the expression $foo + 1 .
The real question is why you want to do this; variable variables are generally a sign of very messy code, and probably some poor choices of data structure. For instance, if you need to select one of a set of variables based on some input, you probably want a hash, and to look up an item using $hash[$item] or similar. If you need something more complex, a switch statement can often cover the cases you actually need.
If for some reason you really need to allow an arbitrary expression like $arr[0] as input and evaluate it at runtime, you could use eval(), but be very very careful of where the input is coming from, as this can be a very easy way of introducing security holes into your code.
FROM PHP DOC
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.
Use
echo ${$a}[0]; // 123
Edit : Based on your edit you can simply have
list($a, $b, $c) = (condition) ? $arr1[0] : $arr2;
Or
$array = (condition) ? $arr1[0] : $arr2;
$a = $array[0];
$b = $array[1];
$c = $array[2];
As pointed out you don't need variable variables. To get a PHP variable variable name containing index (a key) use array_keys() or array_search() or other array parsers. From php's site:
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
You could also use the following (using $var= instead of echo):
$arr[0]=123;
$arr[1]=456;
foreach ($arr as $key => $value) {
echo "arr[{$key}] = {$value} \r\n";
}
Which outputs:
arr[0] = 123
arr[1] = 456
But I don't see why you'd do that, since the whole point of the array is not doing that kind of stuff.

variable value is two strings

Somehow a variable that SHOULD contain only one string (not an array or anything) contain an url, managed to contain two different values;
string(8) "value 1 " string(7) "value 2"
i cannot use this variable because echoing it or using it in another function would print
value 1 value2
which is not what i need, i need only value 1 and i cannot use $var[0]
Two things; how can i do something similar (one variable two strings), and how can i manipulate it.
EDIT : here is the code
public function get_first_image($post) {
$image_id=get_post_thumbnail_id($post->id);
$image_url = wp_get_attachment_image_src($image_id,’large’);
$image_url=$image_url[0];
var_dump($image_url);
return $image_url;
}
the var_dump() results are as mentioned above
Best Regards
Don't reuse $image_url as a variable, this is most likely causing your problem.
You should rename one of your variables:
public function get_first_image($post) {
$image_id = get_post_thumbnail_id($post->id);
$image_array = wp_get_attachment_image_src($image_id,’large’);
$image_url = $image_array[0];
var_dump($image_url);
return $image_url;
}
You question doesn't give a great amount of detail. If you need access to part of a string you can use the explode() function. So if the string contained no spaces between the separate values, you could use $newstring = explode(" ",$oldstring); echo $newstring[0]; This would then give you access to the first part of the string.
I'd recommend you look up string concatenation.
If you can give us further details, we may be able to assist you further.

Variables into array - $array[$var_name] = $var;

I was wondering whether something like this is possible:
$var1 = 1; $var2 = 2;
function varsToArray($param1, $param2...);
and it returns array like this
array([var1] => 1, [var2] => 2).
Simply saying, I'd like arrays keys to be same as variable names. The problem is I don't know how to get variable name as string to put it as key(if possible of course...).
You want to use the compact function methinks.
The built-in PHP function compact() does this.
BTW: I'm going to go ahead and assume that instead of:
function $varsToArray($var1, $var2...);
you actually meant:
function varsToArray($var1, $var2...);
Notice the dollar sign has been removed.

Categories