Dynamically setting a variable in PHP? - php

So i want to deo something like this and not sure how
for($s=0; $s < 5; $s++ ){
$pre_config_query = "select * from preconfig where code = '{$industry_string}_{$s}_{$class_string}'";
$pre_config_station = mysql_query($pre_config_query);
$it_exists = mysql_num_rows($pre_config_station);
if($it_exists>0){
$pre_config = mysql_fetch_assoc($pre_config_station);
$pre{$s} = $pre_config['id'];
I want the end product to have these 5 variables named
print $pre1;
print $pre2;
print $pre3;
print $pre4;
print $pre5;
That have the $pre_config['id'] if present....any ideas

You can use variable variables to accomplish that.
First, define a variable with the desired name:
$varname = "pre$s";
Second, assign a value to it:
$$varname = $pre_config['id'];
That's all!

this works but I'm not sure I'm answering your question.
<?php
for($s=1; $s < 6; $s++ ){
$it_exists=1;
if($it_exists > 0){
$pre_config = array('id'=>rand(10,99));
${"pre".$s} = $pre_config['id'];
}
}
echo $pre1."<br/>";
echo $pre2."<br/>";
echo $pre3."<br/>";
echo $pre4."<br/>";
echo $pre5."<br/>";
?>

Related

How to create a php variable with text and value of another variable

Want to create a php variable using text before and after the value of another variable.
variable variables. But have only seen examples of assignment with no text.
$vsBOA_W[]=$rows['vsBOA_W'];
// BOA = team 3-char abbreviation. Looking for something similar to above but insert 3-char abbreviations based on a input file.
$numOfTeams = 3; // Determined from external source
$teamAbbr = array("BOA","CAA","CHN"); // For simplicity for this example. This array would normally be created from an external source.
for($i=0; $i<$numOfTeams; $i++) { // I know I can use size of array instead of nunOfTeams. That's not the issue.
echo $teamAbbr[$i]."<br>"; // for testing
$$("vs".{'$teamAbbr[$i]'}."_W[]"} = $rows['$$("vs".{'$teamAbbr[$i]'}."_W"}']; // a total guess
}
I expect the end result to look like:
$vsBOA_W[]=$rows['vsBOA_W'];
for BOA
Update #2: I tried the following (breaking down each step) and get the same error on $$TeamWins assignment.
for($i=0; $i<$numOfTeams; $i++) {
echo $teamAbbr[$i]."<br>";
$TeamWins = 'vs' . $teamAbbr[$i] . '_W';
echo "TeamWins=$TeamWins<br>";
$TeamWinsHold = $rows[$TeamWins];
echo "TeamWinsHold=$TeamWinsHold<br>";
$$TeamWins[] = $TeamWinsHold;
}
Update #3:
for($i=0; $i<$numOfTeams; $i++) {
echo $teamAbbr[$i]."<br>";
$TeamWins = 'vs' . $teamAbbr[$i] . '_W';
echo "TeamWins=$TeamWins<br>";
$TeamWinsHold = $rows[$TeamWins];
echo "TeamWinsHold=$TeamWinsHold<br>";
${$TeamWins}[] = $TeamWinsHold;
}
foreach(${$TeamWins} as $value) {
echo "value=$value<br>"; // only displays last element or value assigned from above loop.
}
Update #4 (final):
$teamW = array();
$teamL = array();
for($i=0; $i<$numOfTeams; $i++) {
//echo $teamAbbr[$i]."<br>";
$teamWName = 'vs' . $teamAbbr[$i] . '_W';
$teamLName = 'vs' . $teamAbbr[$i] . '_L';
//echo "teamWName=$teamWName<br>";
//echo "teamLName=$teamLName<br>";
$teamW[$teamWName] = $rows[$teamWName];
$teamL[$teamLName] = $rows[$teamLName];
}
I don't quite understand the interplay with the rows in your example. But going by your guess assignment, you can always simplify, by forming the variable name upfront:
<?php
$rows = ['xFOOy'=>[], 'xBARy'=>[], 'xBAZy'=>[]];
$items = ['FOO', 'BAR', 'BAZ'];
foreach($items as $abbr)
{
$name = 'x' . $abbr . 'y';
${$name}[] = $rows[$name];
}
But, I'd say you'd be better off with a keyed array than variable variables, as it makes for easier inspection, and there is less chance of namespace clashes.

Issues with variable scopes in PHP

I have just written a program to check for the variable scopes in PHP. The code goes like this:
<?php
$value = 1;
function change_value(){
if(some_condition){
$value = 0;
$asset = 1;
}else{
$asset = 0;
}
return $asset;
}
echo $value;
change_value();
echo $value;
?>
Now, the output of the above program is 11.
How can I change the value of $value once it enters the function change_value() ?
Pass the parameter by reference:
<?php
$value = 1;
function change_value(&$value){
if(/* some_condition */){
$value = 0;
$asset = 1;
}else{
$asset = 0;
}
return $asset;
}
echo $value; // echoes 1
$asset = change_value($value);
echo $value; // echoes 0
echo $asset; // echoes 0 or 1 depending on /* some_condition */
?>
Please don't use global ... even if some suggest it.
It's bad. It let's the variable be accessable from all over the script and you will be very confused when you come upon the situation where you access $value in a different script you included and it acts different then...
What you're trying to do, goes against common principles, but.
$GLOBALS['value'] = 0;
Using this inside function will let you change that value, but I suggest you not to do this.
The way others have outlined, is far more right.

Loop through variables with common name

At first glance I think you can get what I'm trying to do. I want to loop though variables with the same name but with a numerical prefix. I also had some confusion about the kind of loop I should use, not sure if a "for" loop would work. The only thing is I can't wrap my head around how php could interpret "on the fly" or fabricated variable. Ran into some trouble with outputting a string with a dollar sign as well. Thanks in advance!
$hello1 = "hello1";
$hello2 = "hello2";
$hello3 = "hello3";
$hello4 = "hello4";
$hello5 = "hello5";
$hello6 = "hello6";
$hello7 = "hello7";
$hello8 = "hello8";
$hello9 = "hello9";
$hello10 = "hello10";
for ( $counter = 1; $counter <= 10; $counter += 1) {
echo $hello . $counter . "<br>";
}
It's generally frowned upon, since it makes code much harder to read and follow, but you can actually use one variable's value as another variable's name:
$foo = "bar";
$baz = "foo";
echo $$baz; // will print "bar"
$foofoo = "qux";
echo ${$baz . 'foo'}; // will print "qux"
For more info, see the PHP documentation on variable Variables.
However, as I already mentioned, this can lead to some very difficult-to-read code. Are you sure that you couldn't just use an array instead?
$hello = array(
"hello1",
"hello2",
// ... etc
);
foreach($hello as $item) {
echo $item . "<br>";
}
Try ${"hello" . $counter}
$a = "hell";
$b = "o";
$hello = "world";
echo ${$a . $b};
// output: world
You can use variable variables as:
for ( $counter = 1; $counter <= 10; $counter += 1) {
echo ${'hello' . $counter } , '<br>';
}
as I guess u not even need to declare $hello1 = "hello1". coz the $counter is incrementing the numbers by its loop.
<?php
for ( $counter = 1; $counter <= 10; $counter += 1) {
echo 'hello' . $counter . "\n";
}
?>
so this is enough to get the output as you want.
the output will be:-
hello1
hello2
hello3
hello4
hello5
hello6
hello7
etc...

php get the variable name from other variable

look at this simple script please
$c1 = $_GET[c1];
$c2 = $_GET[c2];
$c3 = $_GET[c3];
$c4 = $_GET[c4];
$c5 = $_GET[c5];
for($i = 1;$i <=5;$i++)
{
echo $c{$i};//or something else here :/
}
how can i print tha values of variables?
Thanks
You can see on php.net some good examples in the variable page. Read that and take a look at the examples.
Also, below is your piece of code fixed so it can work:
<?php
$c1 = $_GET[c1];
$c2 = $_GET[c2];
$c3 = $_GET[c3];
$c4 = $_GET[c4];
$c5 = $_GET[c5];
for($i = 1;$i <=5;$i++)
{
echo ${"c".$i};
}
You should use an array rather than individual variables.
For reference:
http://php.net/manual/en/language.types.array.php
If these values are closely related, consider changing their name attribute in your HTML/form.
HTML:
<form>
<input type="text" name="c[]" />
<input type="text" name="c[]" />
...
</form>
PHP:
<?php
if(!empty($_GET['c'])) {
foreach($_GET['c'] as $c) {
echo $c;
}
}
?>
Here's a better way of doing it, using Arrays, rather than individual variables, which works easier and more efficiently.
<?php
$array['c1'] = $_GET['c1'];
$array['c2'] = $_GET['c2'];
$array['c3'] = $_GET['c3'];
$array['c4'] = $_GET['c4'];
$array['c5'] = $_GET['c5'];
for ($i=1; $i>=5; $i++) {
echo $array['c' . $i];
}
?>
Perhaps PHP variable variables is what you are looking for.
$i = "c1";
print $$i;
I'll leave it to you to figure out how to construct correct values for 'i'.
This should work..
foreach($_GET as $id => $value){
echo $value;
}
even though this prints out every $_GET.

PHP - Variable inside variable?

$bookA = "123";
$crack = "A";
I want to do something similar to this:
echo $book$crack;
Such that the output is 123.
What is the correct syntax for the echo command?
Thanks.
echo ${"book" . $crack};
These are called variable variables, but you should use arrays instead.
$varname = 'book'.$crack;
echo $$varname;
You might want to use an associative array.
For instance:
$book = array();
$book["A"] = "Some Book";
$crack = "A";
//Later
echo $book[$crack];
This will work:
$bookA = "123";
$crack = "A";
$var = "book$crack";
echo $$var;
Try the following:
echo ${book.$crack};
It works for me.

Categories