php string name as variable - php

$string = "id";
want result to be like
$id = "new value";
How do I code this in php?
Edit..
How about the below?
$column = array("id","name","value");
let say found 3 row from mysql
want result to be like this
$id[0] = "3";
$id[1] = "6";
$id[2] = "10";
$name[0] = "a";
$name[1] = "b";
$name[2] = "c";
$value[0] = "bat";
$value[1] = "rat";
$value[2] = "cat";

Theres 2 main methods
The first is the double $ (Variable Variable) like so
$var = "hello";
$$var = "world";
echo $hello; //world
//You can even add more Dollar Signs
$Bar = "a";
$Foo = "Bar";
$World = "Foo";
$Hello = "World";
$a = "Hello";
$a; //Returns Hello
$$a; //Returns World
$$$a; //Returns Foo
$$$$a; //Returns Bar
$$$$$a; //Returns a
$$$$$$a; //Returns Hello
$$$$$$$a; //Returns World
//... and so on ...//
#source
And the second method is to use the {} lik so
$var = "hello";
${$var} = "world";
echo $hello;
You can also do:
${"this is a test"} = "works";
echo ${"this is a test"}; //Works
I had a play about with this on streamline objects a few weeks back and got some interesting results
$Database->Select->{"user id"}->From->Users->Where->User_id($id)->And->{"something > 23"};

You are looking for Variable Variables
$$string = "new value";
will let you call
echo $id; // new value
Later in your script

Second answer in response to your edit:
$result = mysql_query($sql);
$num = mysql_num_rows($result);
$i = 0;
$id = array();
$name = array();
$value = array();
if ($num > 0) {
while ($row = mysql_fetch_assoc($result)) {
$id[$i] = $row['id'];
$name[$i] = $row['name'];
$value[$i] = $row['value'];
$i++;
}
}
This loops around your result, using the counter $i as the key for your result arrays.
EDIT
Additional answer in response to your comment:
while ($row = mysql_fetch_assoc($result)) {
foreach($row as $column_name => $column_value) {
$temp_array[$column_name][$i] = $column_value;
}
$i++;
}
foreach ($temp_array as $name => $answer) {
$$name = $answer;
}
This code creates a temporary multidimensional array to hold the column names and values the loops around that array to create your variable variable arrays. As a side not I had to use the temp array as $$column_name[$i] doesn't work, I would love to see alternative answers to this problem.
Final note #Paisal, I see you have never accepted an answer, I wouldn't have put this much effort in if I had seen that before!

You can do this
$$string = "new value";
juste double $

Are you referring to variable variables?
That would accomplish something like this:
$string = "id";
$$string = "new value";
This produces a variable $id with the value "new value".

Don't do that. Just use an array.
$arr[$string] = 'new value';
ref: How do I build a dynamic variable with PHP?

Try this :
$result = mysql_query($sql);
$num_rows = mysql_num_rows($result);
$i = 0;
if ($num_rows) {
while ($row = mysql_fetch_assoc($result)) {
foreach($row AS $key => $value) {
${$key}[$i] = $value;
}
$i++;
}
}

For those of us who need things explained in great detail...
// Creates a variable named '$String_Variable' and fills it with the string value 'id'
$String_Variable = 'id';
// Converts the string contents of '$String_Variable', which is 'id',
// to the variable '$id', and fills it with the string 'TEST'
$$String_Variable = 'TEST';
// Outputs: TEST
echo $id;
// Now you have created a variable named '$id' from the string of '$String_Variable'
// Essentially: $id = 'Test';

Related

`json_encode` not working with explode

I have a string containing numbers separated by comma. ie, 1,2,3,6.... I have removed the comma using explode. Now i want to match the corresponding values in database.
My Code is,
$color = "1,2,3,9,5";
$color_split = explode(",", $color);
foreach($color_split as $item)
{
$select_color = "SELECT * FROM tbl_product_color WHERE color_id = '$item'";
$select_color_q = mysqli_query($c, $select_color) or die(mysqli_error($c));
$length = mysqli_num_rows($select_color_q);
if($length > 0)
{
while($select_color_r = mysqli_fetch_object($select_color_q))
{
$var[] = $select_color_r;
}
$var = json_encode($var);
echo '{"color_list":'.$var.'}';
}
else
{
$arr = array('status'=>"notfound");
echo '{"color_list":['.json_encode($arr).']}';
}
}
Now the output is,
{"color_list":[{"color_id":"1","color_name":"White","color_code":"#f2f2f2"}]}
and one error,
Fatal error: [] operator not supported for strings in C:\wamp\www\jithin\get_color.php on line 18
line 18 contains $var[] = $select_color_r;
My required output is,
{"color_list":[{"color_id":"1","color_name":"White","color_code":"#f2f2f2"},{"color_id":"2","color_name":"Black","color_code":"#000000"},{"color_id":"3","color_name":"Red","color_code":"#F000000"},...]}
You don't need to use foreach and explode over here you can simply update your MySql query and code like as
$color = "1,2,3,9,5";
$select_color = "SELECT * FROM tbl_product_color WHERE color_id IN ($color)";
$select_color_q = mysqli_query($c, $select_color) or die(mysqli_error($c));
$arr['color_list'] = array();
if(mysqli_num_rows($select_color_q) > 0)
{
while($select_color_r = mysqli_fetch_object($select_color_q))
{
$var[] = $select_color_r;
}
}else{
$var = array('status'=>"notfound");
}
$arr['color_list'] = $var;
echo json_encode($arr);
you set $var as string in here :
$var = json_encode($var);
but in the next step of foreach you want to use $var as array.
$var[] = $select_color_r;
just remove the following line :
$var = json_encode($var);
and change this line :
echo '{"color_list":'.$var.'}';
to
echo '{"color_list":'.json_encode($var);.'}';

PHP min not working correctly

I have an array with 3 values(56.767, 360.997, 579.728). These are in an array($distance).
Well, when I run the min($distance) I get '360.997'. What gives?
<?php
include('mysql_connect.php');
$MasterState = 'CA';
$query = 'select * from estes_term where Dest_State = "'.$MasterState.'"';
$result = mysql_query($query);
if($result) {
$row = #mysqli_fetch_row($result);
}
$Term_Zip = array();
$Distance = array();
$i = '0';
while ($row = mysql_fetch_array($result, MYSQLI_ASSOC)) {
$Term_Zip[] = $row['Term_Zip'];
$Distance_xml = file_get_contents('http://zipcodedistanceapi.redline13.com/rest/ua6z0ep0djB3zHGz5Z40hONMVc8yuXgY8nx8BX8OhKSRrzqxzvyRjmDeyMM3J32S/distance.xml/90077/'.$Term_Zip[$i].'/mile');
$Distance[] = $Distance_xml;
$i++;
}
echo '<pre>';
var_dump($Term_Zip);
var_dump($Distance).'<br />';
$test1 = min($Distance);
$test = (array_keys($Distance, min($Distance)));
echo '<br />';
echo 'Min'.min($Distance);
?>
As #Rocket pointed out, your variables are stored as strings, not floats. This, the character "3" is smaller than "5", so it's the first one. To avoid this use Type Juggling or floatval() in your code to assure your vars are float as:
$Distance[] = floatval(trim($Distance_xml));
Do like this... We are converting all the array elements to float using array_map and then finding the min value from it.
<?php
$arr= array(56.767, 360.997, 579.728);
echo min(array_map('floatval',$arr));
OUTPUT :
56.767
EDIT :
To get the key , you can make use of array_search()
$key = array_search(min(array_map('floatval',$arr)), $arr);

print name using for loop php

Using for loop in PHP can we have numbers associate with a variable name?
ex:
$name1="hi";
$name2="khj";
for($i=0;$i<=2;$i++)
{
echo ..
}
How can we print $name1 and $name2 using for loop?
Thanks!
Yes this is called variable interpolation.
$name1="hi";
$name2="khj";
for($i=1;$i<=2;$i++) {
$var = 'name' . $i;
echo $$var;
}
Note: There are multiple syntaxes for variable interpolation in PHP. Also, I modified your loop to start at 1.
for($i = 1; $i <= 2; $i++)
{
echo $name{$i};
}
It would be way easier to put it in an array though, that's what we have them for.
$names = array();
$names[1] = 'A';
$names[2] = 'B';
foreach($names as $name)
{
echo $name;
}
put this in the for loop:
echo ${'name'.$i}."\n";
Better to use something like:-
$names[] = $name1;
$names[] = $name2;
foreach($names as $name){
echo $name;
}
This print the name1 and name2 .And i value must be start from 1
for($i=1;$i<=2;$i++)
{
echo ${'name'.$i}."<br>";
}

php loop statement question

I'm wondering if it is possible to loop a variable within a variable? Here is something I want to setup:
$var1 = Benjamin
$var2 = George
$var3 = Abraham
and probably echo out something like
<li>Benjamin</li>
<li>George</li>
<li>Abraham</li>
but I want to know, if I want to add $var4 = ..., $var5 = ..., is there a way I can do this all in a loop? I'm thinking having an empty() function that'll loop the variable names/numbers until reaches the first empty variable?
You could store them in an array.
$names = array('Mike', 'Jim', 'Tom', 'Stacy');
foreach($names as $name){
echo $name;
}
As seen here: http://www.ideone.com/f7Ce7
In PHP you can do this:
$var1 = "foo";
$var2 = "bar";
$name = "var1";
$i=1;
while( !is_null( $$name ) ) {
echo '<li>' . $$name . '</li>';
$i++;
$name = "var$i";
}
but a better solution may be using an array and a foreach
This sounds like you want to use arrays and foreach. Am I missing something?
$presidents = array(
'Benjamin', 'George', 'Abraham'
);
foreach($presidents as $pres) {
echo "$pres\n";
}
$var=array('Benjamin', 'George', 'Abraham');
foreach ($var as $name){
echo $name;
}
A better solution would be arrays.
define it as:
$names = array(0=>"Benjamin",1=>"George",2=>"Abraham");
Then loop through it with:
foreach ($names as $id=>$name)
{
echo $name;
}
Then reference a name with $names[0], if you want to add another use $names[] = 'William';
Look up more information at:http://php.net/manual/en/language.types.array.php
This solution doesn't require the use of an array.
$var1 = 'Benjamin';
$var2 = 'George';
$var3 = 'Abraham';
//add as many variables as you want
$i = 0;
$currentVariable = 'var'.$i;
while (isset($$currentVariable)) {
//process variable
echo $$currentVariable;
$i++;
}

php string name as variable in array

how take string from array define as new array,
how to code in php
$column = array("id","name","value");
let say found 3 row from mysql
want result to be like this
$id[0] = "1";
$id[1] = "6";
$id[2] = "10";
$name[0] = "a";
$name[1] = "b";
$name[2] = "c";
$value[0] = "bat";
$value[1] = "rat";
$value[2] = "cat";
I want to take string from $column array define as new array.
how to code it?
or if my question is stupid , my please to have suggestion.
thank you.
Answer I made on your previous question:
$result = mysql_query($sql);
$num = mysql_num_rows($result);
$i = 0;
if ($num > 0) {
while ($row = mysql_fetch_assoc($result)) {
foreach($row as $column_name => $column_value) {
$temp_array[$column_name][$i] = $column_value;
}
$i++;
}
foreach ($temp_array as $name => $answer) {
$$name = $answer;
}
}
I can't see why you'd want to model your data like this, you're asking for a world of hurt in terms of debugging. There are "variable variables" you could use to define this, or build global variables dynamically using $GLOBALS:
$somevar = "hello"
$$somevar[0] = "first index"; // creates $hello[0]
$GLOBALS[$somevar][0] = "first index"; // creates $hello[0] in global scope
try
$array = array();
foreach ($results as $r){
foreach ($column as $col ){
$array[$col][] = $r[$col];
}
}
extract ($array);
or you can simply do this
$id = array();
$name = array();
$value = array();
foreach ( $results as $r ){
$id[] = $r['id']; // or $r[0];
$name[] = $r['name'];
$value[] = $r['value'];
}
Hope this is what you asked
This is pretty dangerous, as it may overwrite variables you consider safe in your code. What you're looking for is extract:
$result = array();
while ($row = mysql_fetch_array($result))
foreach ($column as $i => $c)
$result[$c][] = $row[$i];
extract($result);
So, if $result was array( 'a' => array(1,2), 'b' => array(3,4)), the last line defines variables $a = array(1,2) and $b = array(3,4).
You cannot use variable variables right on for this, and you shouldn't anyway. But this is how you could do it:
foreach (mysql_fetch_something() as $row) {
foreach ($row as $key=>$value) {
$results[$key][] = $value;
}
}
extract($results);
Ideally you would skip the extract, and use $results['id'][1] etc. But if you only extract() the nested array in subfunctions, then the local variable scope pollution is acceptable.
There is no need for arrays or using $_GLOBALS, i believe the best way to create variables named based on another variable value is using curly brackets:
$variable_name="value";
${$variable_name}="3";
echo $value;
//Outputs 3
If you are more specific on what is the array you receive i can give a more complete solution, although i must warn you that i have never had to use such method and it's probably a sign of a bad idea.
If you want to learn more about this, here is a useful link:
http://www.reddit.com/r/programming/comments/dst56/today_i_learned_about_php_variable_variables/

Categories