Here are the variables:
$fake= 'cool';
$fake1 = 'not cool';
$hope= '1';
The idea is to combine $fake and the $hope to create the variable $fake1. The idea is that if the $hope variable was randomized it could generate a random variable: $fake1, $fake2, $fake3, etc. Right now I either get an error or just the values of $fake and $hope next to each other not the new variable.
You should use an "array" for this:
$list = array('cool', 'not cool');
$random_item = array_rand($list);
Using variable-named variables is always messy and this is exactly what arrays are for.
Ben's comment above does probably exactly what you're looking for, but if you're in PHP5 you can also do something like:
$varname = $fake . $hope;
$$varname = "horray";
You can try
$fake = array(
"fake1" => "Cool",
"fake2" => "Bad",
"fake3" => "Fish",
"fake4" => "Next",
"fake5" => "Wow");
list($a, $b) = array_rand($fake, 2);
echo $fake[$a] . " " . $fake[$b]; // This would always change
Related
Let's say I have an array of strings that I use to create variable variables:
$var_arr = ["item1", "item2", "item3"];
foreach ($var_arr as $item) {
$$item = array();
}
Then elsewhere in my code I have to recreate the variable variable based on a different data source:
$user_input = [ "prod1" => "widget", "qty1" => 3, "prod2" => "thingy", "qty2" => 1, "prod3" => "dingus", "qty3" => 7 ];
foreach ($user_input as $key => $value) {
$a = "item" . substr($key, -1);
array_push($$a, $value);
}
Are $$item and $$a the same variable, or do they reference different blocks of memory?
Both are the same what you need to consider here is that you are just referencing a variable through each assignment here:
<?php
$hello ="hello in variable";
$array_hello = ["hello","Yellow"];
$hello_var = "hello";
$item = $array_hello[0];
echo $$hello_var;
echo $$item; //result same as above result
?>
Here one thing to notice is ${$variable_name_string} is just using $variable_name_string to know the name of the variable you want so both will be accessing the same memory block because you are referencing same variable here.
One more thing to notice here is the change in interpretation in PHP 7 from PHP 5
Expression $$foo['bar']['baz'] PHP 5 interpret it as ${$foo['bar']['baz']} while PHP 7 interpret it as ($$foo)['bar']['baz']
Refer PHP manual for more
I'm trying to execute variable which part of it is a string.
Here it is:
$row = array(
'index_1' => array(
'index_2' => 'my-value'
)
);
$pattern = "['index_1']['index_2']";
I tried to do it in following ways:
// #1
$myValue = $row{$pattern};
// #2
$myValue = eval("$row$pattern");
I also trying to get it working with variable variable, but not successful.
Any tips, how should I did it? Or myabe there is other way. I don't know how may look array, but I have only name of key indexes (provided by user), this is: index_1, index_2
You could use eval but that would be quite risky since you say the values come from user input. In that case, the best way might be to parse the string and extract the keys. Something like this should work:
$pattern = "['index_1']['index_2']";
preg_match('/\[\'(.*)\'\]\[\'(.*)\'\]/', $pattern, $matches);
if (count($matches) === 3) {
$v = $row[$matches[1]][$matches[2]];
var_dump($v);
} else {
echo 'Not found';
}
This can help -
$row = array(
'index_1' => array(
'index_2' => 'my-value'
)
);
$pattern = "['index_1']['index_2']";
$pattern = explode("']['", $pattern); // extract the keys
foreach($pattern as $key) {
$key = str_replace(array("['", "']"), '', $key); // remove []s
if (isset($row[$key])) { // check if exists
$row = $row[$key]; // store the value
}
}
var_dump($row);
Storing the $row in temporary variable required if used further.
Output
string(8) "my-value"
If you always receive two indexes then the solution is quite straight forward,
$index_1 = 'index_1';// set user input for index 1 here
$index_2 = 'index_2';// set user input for index 2 here
if (isset($row[$index_1][$index_2])) {
$myValue = $row[$index_1][$index_2];
} else {
// you can handle indexes that don't exist here....
}
If the submitted indexes aren't always a pair then it will be possible but I will need to update my answer.
As eval is not safe, only when you know what you are ding.
$myValue = eval("$row$pattern"); will assign the value you want to $myValue, you can add use return to make eval return the value you want.
here is the code that use eval, use it in caution.
demo here.
<?php
$row = array(
'index_1' => array(
'index_2' => 'my-value'
)
);
$pattern = 'return $row[\'index_1\'][\'index_2\'];';
$myValue = eval($pattern);
echo $myValue;
My Php function loops trough the mysql table and for each row it sets the row name as $var and the row value to $val.
foreach($row as $var => $val) {...
Now I want to set the received rowname ($var) as a new variable.
This example is not right but to explain my thoughts ; $name$var = $val
If $var would be = rowname1
then the new variable would be $rowname1 = value1
Any ideas how to achieve this ?
Thanks.
You can use variable variables to do that:
foreach(...) {
$$var = $val;
}
But cleaner would be to use an array:
foreach(...) {
$var_names[] = array($var => $val);
}
<?php
$array = array(
'go' => 'something1',
'go2' => 'something2',
'go3' => 'something3',
'go4' => 'something4',
'go5' => 'something5',
);
foreach ($array as $key => $val) {
${$key} = $val;
}
print $go;
?>
EXAMPLE
or you could use the $$ way explained here:
Read more about Variable Variables...
You can use it like ${$var} = $val. Curly brackets are there just for convenience and readability. $$var = $val should also work.
You can create variables with dynamic names on the fly using strings! This is supported in the documentation provided here
A quick example:
// This now holds the string hello
$variableName = 'hello';
// This creates the variable 'hello' and contains the value test
$$variableName = "test";
echo $hello;
With the above example complete you will be able to create a variable name with the key + value strings as follows:
$count = 1;
foreach($row as $var => $val)
{
$varName = $var.$count;
$$varName = $val;
$count++;
}
This will create column_name1, column_name2 etc.
I feel the need to add a little discretion as this is not common or best practice. The best way to handle this information would be to take the $key => $val pair and store it into a separate variable or parse through them. By doing this you are basically throwing away all of the ease of use that is using arrays.
Also, side note:
You can also dynamically call on methods this way.
function test()
{
echo "test yar";
}
$method = "test";
$method();
Thanks for the help below, however, I'm still having some problems, I'll try and explain further:
I have a variable as follows:
$value['questions'];
Now, I need to do a check in a loop, so I have this piece of code in the loop:
if($results[$value['questions']]==4){blah blah blah};
but the problem I am having is that the value of $value['questions'] is q1 but I need the q1 to be a string (i.e. inside quotes '') in the $results section of the code, so the $results element should look like this...
if($results['q1']==4){blah blah blah};
currently it looks like this
if($results[q1]==4){blah blah blah};
Make sense?
Thanks again for the help.
Hi all,
I hope there is a simple solution!
I have a variable:
$results['q1'];
Is it possible to have the 'q1' element as a variable, something like this:
$results['$i[question]'];
Have not been able to find a solution on Google and researching the PHP manuals...
Anyone got a suggestion/ solution?
Thanks,
Homer.
Yes, it is possible to use a variable as indice, when accessing an array element.
As an example, consider this portion of code :
$results = array(
'a' => 'sentence a',
'b' => 'hello !',
);
$indice = 'a';
echo $results[$indice];
Which will give the following output :
sentence a
Here, $indice is a quite simple variable, but you could have used whatever you wanted between the [ and ], like, for instance :
functions : $results[ my_function($parameter) ]
array element : $result[ $my_array['indice'] ]
Which seems to be what you want to do ?
object property : $result[ $obj->data ]
...
Basically, you can use pretty much whatever you want there -- as long as it evaluates to a scalar value (i.e. a single integer, string)
In your specific case, you could have $results declared a bit like this :
$results = array(
'q1' => 'first question',
'q2' => 'second question',
);
And $i would be declared this way :
$i = array(
'question' => 'q1'
);
Which means that $i['question'] would be 'q1', and that the following portion of code :
echo $results[ $i['question'] ];
Would get you this output :
first question
Edit : To answer the specific words you used in the title of your question, you could also use what's called variable variable in PHP :
$variable = 'a';
$indice = 'variable';
echo $results[ $$indice ];
Here :
$indice is 'variable'
and $$indice is 'a'
which means you'll get the same output as before
And, of course, don't forget to read the Arrays section of the PHP manual.
The Why is $foo[bar] wrong? paragraph could be of interest, especially, considering the example you firt posted.
Edit after the edit of the OP :
If $value['questions'] is 'q1', then, the two following portions of code :
if($results[$value['questions']]==4){blah blah blah}
and
if($results['q1']==4){blah blah blah}
should do exactly the same thing : with $results[$value['questions']], the $value['questions'] part will be evaluated (to 'q1') before the rest of the expression, and that one will be the same as $results['q1'].
As an example, the following portion of code :
$results = array(
'q1' => 4,
'q2' => 6,
);
$value = array('questions' => 'q1');
if($results[$value['questions']]==4) {
echo "4";
}
Outputs 4.
You can do:
$results[$i['question']];
This will first access the array $i to get the value corresponding to the key 'question'. That value will be used as the key into the array $results.
Your way: $results['$i[question]'];
is actually trying to get the value corresponding to the key '$i[question]' in the array $results. Since the key is in single quote, variable interpolation does not happen and the entire string is treated literally.
Alternatively you can also do:
$results["$i[question]"]; // using double quotes also works.
Example:
$arr1 = array('php' => 'zend', 'java' => 'oracle');
$arr2 = array('p' => 'php', 'j' => 'java');
echo $arr1[$arr2['p']]; // prints zend.
echo $arr1["$arr2[p]"]; // prints zend.
<?php
$result['q1'];
// is equivalent to
$index = 'q1';
$result[ $index ];
Now $index can be as complex as you want it to be. For example something like this is also possible:
$result[ 'q' . round( $someArray[$i] / 2 ) ];
CODE
<?php
$results = array(
'q1' => 'This is a result called q1.',
'q2' => 'So, can you access this?',
'$i[question]' => 'This is a result called $i[question]',
);
$i = array(
'question' => 'q2',
'answer' => 'Yes.'
);
echo '<pre>';
echo $results['q1'] . "\n"; // Using Array's is easy -
echo $results['$i[question]'] . "\n"; // all you gotta do is make sure
echo $results[$i['question']] . "\n"; // that you understand how
echo $i['answer']; // the keys work.
?>
OUTPUT
This is a result called q1.
This is a result called $i[question]
So, can you access this?
Yes.
Ok this might sound like a dumb question but bear with me. I am trying to make it so that when people go to example.php?id=1, example.php?id=2, example.php?id=3 etc they see different data called from an included file filling in the blanks.
I have a variable called $offername and I want to display $offer1name, $offer2name, $offer3name in that space, depending on what $_GET['id'] says. Ideally, when someone goes to example.php?id=2, $offername will equal $offer2name.
I want to do something like this:
$offername = $offer.$_GET['id'].name
But of course that doesn't work. What should I do?
A much cleaner solution is to just use multidimensional arrays.
e.g., instead of
$offername = ${offer.$_GET['id'].name};
use
$offername = $offer[$_GET['id']]['name'];
and define $offer like so:
$offer = array(
1 => array(
'name' => 'firstoffer',
),
2 => array(
'name' => 'secondoffer',
),
3 => array(
'name' => 'thirdoffer',
),
);
I find variable variables difficult to read, and most of the time when I see them used, an array would be much better.
This should work:
$var = 'offer' . $_GET['id'] . 'name';
$offername = $$var;
See the page on variable variables for more.
PHP can use variable variables
So you can have $offer_variable_name = 'offer' . $_GET['id'] . 'name';
And then use something like $offername = $$offer_variable_name.
You can in addition to the other solutions do:
$offername = ${'offer' . $_GET['id'] . 'name'};