creating variable name by concatenating strings in php - php

I have a file named questions.php with an array as follows :
$question12 = array("Which is the tallest mountain","Mt Everest");
I am including this file in another file as follows :
require_once('questions.php');
$var = 12;
$question = '$question'.$var.'[0]';
echo $question;
The above code just outputs the following string (not the contents of the variable):
$question12[0]
But I want the variable $question to contain the string present in $question12[0].
How do I accomplish this?

Variable variable is not recommended, but the answer is below:
$question = ${'question'.$var}[0];

You're looking for variable variables.
$id = 12;
$q = "question{$id}";
$q = $$q[0];
You should seriously consider looking into multidimensional arrays to stop having multiple arrays.

Just use $question12[0]. It will give you the desired output.
Using the $var you can do it like this:-
$question = ${'question'. $var}[index];

Sorry, im going to get some hate for mentioning something evil but still it is one of the options
<?php
$question12 = array("Which is the tallest mountain","Mt Everest");
$var = 12;
$question = '$question'.$var.'[0]';
eval("echo $question;");
?>
P.S: eval() is that evil

Related

Can I use a Variable to access the property name of an object?

Let's assume I have the following...
$current_user->ID = 3;
Let's also assume I have the following...
$read = $recipient->read_3;
Note that that the number in the $recipient->read_ property name can change so I don't actually know there is a $recipient->read_3;. I want get the name (e.g. 3) from the value of $current_user->ID to add to $recipient->read_ to get the correct property name.
How do I do that?
I would love to do this...
$read = $recipient->read_$current_user->ID; but that is not correct... What is correct?
You can save it in a variable and use it. Here is an example:
$object = new stdClass();
$object->read_3 = '3';
$id = 3;
$read = 'read_'.$id;
echo $object->$read;
Output:
3
Based on the answer from #majed-badawi I came up with the following:
$num = "read_".$current_user->ID;
$read = $recipient->$num;
You could use try using PHP variable variables. These let you create dynamic variables so you can do this:
$propname = "read_".$current_user->ID;
$read = $recipient->{$propname};
You can find out more about variable variables here: PHP.net variable variables

Get a variable name from database

I'm a little confused - how do I get a variable name stored to a database?!
Record in the database is a string: "$test"
The variable $user is set before the records a fetched from database. So I want to "convert" this string to a real variable to get the value of it.
The following didn't work:
// $test is set to 'bla'
$test = 'bla';
// $var is the value from the database
$var = '$test';
// print $test
echo ${$var};
I know that it would work if I remove the '$' from the database record
$var = 'test';
echo $$var;
But how to handle this without?
String replace in better option, if you don't want to replace $ you can use eval function:
$test = 'bla';
$var = '$test';
eval("\$var = \"$var\";");
echo $var; //output: bla
I was facing a similar problem just now.
Here is what I did:
$res[0] is obtained from mysql_fetch_array() and it contains another query which has $variable embedded.
$qry="select query from sql_list where id=".$sql_id;
$result=mysql_query($qry);
$res=mysql_fetch_array($result);
eval("\$qry_2 = \"$res[0]\";");
mysql_query($qry_2)
It works! Maybe someone can suggest a better way.
This is 3 years later but since no one give you your answer, maybe this will help you or the next person searching for this.
From what I understand, you already declared a variable and stored the name of that var in the db.
$var = '$test'; // from db
$var[0] = ''; // remove first letter, simple & much faster than ( trim or substr )
//content of var
$var_content = ${$var};

Using array value with index as Variable Variable

The title may be a little confusing. This is my problem:
I know you can hold a variable name in another variable and then read the content of the first variable. This is what I mean:
$variable = "hello"
$variableholder = 'variable'
echo $$variableholder;
That would print: "hello". Now, I've got a problem with this:
$somearray = array("name"=>"hello");
$variableholder = "somearray['name']"; //or $variableholder = 'somearray[\'name\']';
echo $$variableholder;
That gives me a PHP error (it says $somearray['name'] is an undefined variable). Can you tell me if this is possible and I'm doing something wrong; or this if this is plain impossible, can you give me another solution to do something similar?
Thanks in advance.
For the moment, I could only think of something like this:
<?php
// literal are simple
$literal = "Hello";
$vv = "literal";
echo $$vv . "\n";
// prints "Hello"
// for containers it's not so simple anymore
$container = array("Hello" => "World");
$vv = "container";
$reniatnoc = $$vv;
echo $reniatnoc["Hello"] . "\n";
// prints "World"
?>
The problem here is that (quoting from php: access array value on the fly):
the Grammar of the PHP language only allows subscript notation on the end of variable expressions and not expressions in general, which is how it works in most other languages.
Would PHP allow the subscript notation anywhere, one could write this more dense as
echo $$vv["Hello"]
Side note: I guess using variable variables isn't that sane to use in production.
How about this? (NOTE: variable variables are as bad as goto)
$variablename = 'array';
$key = 'index';
echo $$variablename[$key];

pChart variables in arrays

I am just editing the Naked example of pChart, I have setup all of my MySQL information to retrive the AddPoints from the database.
This uses something like the below.
$DataSet->AddPoint(array(1,2,3,4,5,6,7,8,9));
When I attempt to do
$var = '1,2,3,4,5,6,7,8,9';
$DataSet->AddPoint($var);
It doesn't work, but when I do
$var = array('1,2,3,4,5,6,7,8,9');
$DataSet->AddPoint($var);
it does work.
I have also tried:
$var2 = "1,2,3,4,5,6,90";
$var = array("$var2");
$DataSet = new pData;
$DataSet->AddPoint($var);
Any suggestions?
Simple you must provide array to this method:
$DataSet->AddPoint()
I am not sure why you are not giving array but if you want to give a string seperated by comma. You could do this way:
$DataSet->AddPoint(explode(',', '1,2,3,4,5,6,90'));

Getting object variable using string + variable

I would like to do something like this:
echo $myObject->value_$id but I don't know proper syntax and I'm not sure if it is possible.
$id is some PHP variable, for example has value 1. In the end, I would like to get $myObject->value_1 but the number part (1) should be dynamic.
The feature is called variable properties:
<?php
$myObject = (object)NULL;
$myObject->value_1 = 'I am value nr 1';
$id = 1;
echo $myObject->{"value_$id"};
This works:
$variableName = 'value_whatever_1337';
echo $myObject->$variableName;
$name = "value_" . $id;
echo $myObject->$name;

Categories