how can i print var name instead var value in php?
Like this code:
$Tree = "abcd";
$str = "zwd";
i want to print something like this:
tree = abcd
str = zwd
please help me
You may want to take a look at compact function
<?php
$city = "San Francisco";
$state = "CA";
$event = "SIGGRAPH";
$location_vars = array("city", "state");
$result = compact("event", "nothing_here", $location_vars);
// print_r($result);
?>
Then print the key and its value,
foreach($result as $key => $value)
{
echo $key . " : " . $value;
}
What you maybe looking for is
echo 'Tree = ' . $Tree;
echo '<br>';
echo 'str = ' . $str;
I am pretty sure OP meant above, btw for expert level programmers, Why this question is paradoxical in nature, is lets say you want to print/output the name of variable $xyz. See....
...did you notice...
....that in order to print the name of a variable you had to actually type the name of the variable in the first place! How else would you refer to that variable!!! And for that the above method of concatenation is best suited :)
Here someone with sane mentality tried to explain better.
I think what you want is this:
$array = array('Tree' => 'abcd', 'str' => 'zwd');
foreach ($array as $name => $value) {
echo $name . ' = ' . $value;
}
If you want to print variable names not writing it by yourself you should use get_defined_vars() as follow :
$var1 = 'I am ';
$what = array_search($var1, get_defined_vars(), true);
printf($var1.'%s', $what); // I am var1
Related
I am using a URL to fetch data stored/shown within URL. I get all the value of variable using $_REQUEST['v_name'] but if there is a array in URL how can i retrieve that value.
For Example:
WWW.example.com/rooms?&hid=213421&type=E
I got the value hid and type using
$hid=$_REQUEST['hid'];
but in URL like:
WWW.example.com/rooms?&rooms=2&rooms[0].adults=2&rooms[0].children=0&rooms[1].adults=2&rooms[1].children=0
how can i retrieve value of adults and children in each room.
please help.
Thanks in Advance
You could also try something like this, since most of your original $_REQUEST isn't really an array (because of the .s in between each key/value pair):
<?php
$original_string = rawurldecode($_SERVER["QUERY_STRING"]);
$original_string_split = preg_split('/&/', $original_string);
$rooms = array();
foreach ($original_string_split as $split_one) {
$splits_two[] = preg_split('/\./', $split_one);
}
foreach ($splits_two as $split_two) {
if (isset($split_two[0]) && isset($split_two[1])) {
$split_three = preg_split('/=/', $split_two[1]);
if (isset($split_three[0]) && isset($split_three[1])) {
$rooms[$split_two[0]][$split_three[0]] = $split_three[1];
}
}
}
// Print the output if you want:
print '<pre>' . print_r($rooms, 1) . '</pre>';
$valuse = $_GET;
foreach ($valuse as $key=>$value)
{
echo $key .'='. $value. '<br/>';
}
while($fetchres = mysql_fetch_array($searchquery)) {
$v1 = $fetchres['v1']; $v2 = $fetchres['v2']; $v3 = $fetchres['v3'];
$v4 = $fetchres['v4']; $v5 = $fetchres['v5'];
$v6 = $fetchres['v6'];
$v7 = $fetchres['v7'];
}
Hi! How can I set this columns automatically? I mean my system automatically adds a column. For example my system adds a new column 'v8'. But in my code, I only inputted until v7. How can I automatically code this fetching of query by depending on how many columns my system automatically made? Thanks.
Use extract.
while ($row = mysql_fetch_assoc($searchQuery))
{
// Extract the keys of the array into the local symbol table.
extract($row);
// Now, all variables exist and you can echo them like this:
echo $v1;
echo $v8;
}
You still need to know the names of the variables. If you just want to echo everything inside, use foreach with a key assingnment:
while ($row = mysql_fetch_assoc($searchQuery))
{
foreach($row as $key => $value)
{
echo "$key: $value\n"; // Will output something like 'v1: foo' and 'v2: bar', separated by newlines.
}
}
If you really want to do this, you can use extract($fetchres).
More info about extract
Example:
$fetchres = array('v1'=>'foo', 'v2'=>'bar');
extract($fetchres);
echo '$v1 is ' . $v1 . 'and $v2 is ' . $v2;
You could use variable variables for that, although I think this is a really bad idea.
I think you actually want this:
while ($fetchres = mysql_fetch_array($searchquery)) {
foreach ($fetchres as $key => $value) {
echo $key . ': ' . $value . PHP_EOL;
}
}
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++;
}
$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';
Let's say I have this:
$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
foreach($array as $i=>$k)
{
echo $i.'-'.$k.',';
}
echoes "john-doe,foe-bar,oh-yeah,"
How do I get rid of the last comma?
Alternatively you can use the rtrim function as:
$result = '';
foreach($array as $i=>$k) {
$result .= $i.'-'.$k.',';
}
$result = rtrim($result,',');
echo $result;
I dislike all previous recipes.
Php is not C and has higher-level ways to deal with this particular problem.
I will begin from the point where you have an array like this:
$array = array('john-doe', 'foe-bar', 'oh-yeah');
You can build such an array from the initial one using a loop or array_map() function. Note that I'm using single-quoted strings. This is a micro-optimization if you don't have variable names that need to be substituted.
Now you need to generate a CSV string from this array, it can be done like this:
echo implode(',', $array);
One method is by using substr
$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
$output = "";
foreach($array as $i=>$k)
{
$output .= $i.'-'.$k.',';
}
$output = substr($output, 0, -1);
echo $output;
Another method would be using implode
$array = array("john" => "doe", "foe" => "bar", "oh" => "yeah");
$output = array();
foreach($array as $i=>$k)
{
$output[] = $i.'-'.$k;
}
echo implode(',', $output);
I don't like this idea of using substr at all, since it's the style of bad programming. The idea is to concatenate all elements and to separate them by special "separating" phrases. The idea to call the substring for that is like to use a laser to shoot the birds.
In the project I am currently dealing with, we try to get rid of bad habits in coding. And this sample is considered one of them. We force programmers to write this code like this:
$first = true;
$result = "";
foreach ($array as $i => $k) {
if (!$first) $result .= ",";
$first = false;
$result .= $i.'-'.$k;
}
echo $result;
The purpose of this code is much clearer, than the one that uses substr. Or you can simply use implode function (our project is in Java, so we had to design our own function for concatenating strings that way). You should use substr function only when you have a real need for that. Here this should be avoided, since it's a sign of bad programming style.
I always use this method:
$result = '';
foreach($array as $i=>$k) {
if(strlen($result) > 0) {
$result .= ","
}
$result .= $i.'-'.$k;
}
echo $result;
try this code after foreach condition then echo $result1
$result1=substr($i, 0, -1);
Assuming the array is an index, this is working for me. I loop $i and test $i against the $key. When the key ends, the commas do not print. Notice the IF has two values to make sure the first value does not have a comma at the very beginning.
foreach($array as $key => $value)
{
$w = $key;
//echo "<br>w: ".$w."<br>";// test text
//echo "x: ".$x."<br>";// test text
if($w == $x && $w != 0 )
{
echo ", ";
}
echo $value;
$x++;
}
this would do:
rtrim ($string, ',')
see this example you can easily understand
$name = ["sumon","karim","akash"];
foreach($name as $key =>$value){
echo $value;
if($key<count($name){
echo ",";
}
}
I have removed comma from last value of aray by using last key of array. Hope this will give you idea.
$last_key = end(array_keys($myArray));
foreach ($myArray as $key => $value ) {
$product_cateogry_details="SELECT * FROM `product_cateogry` WHERE `admin_id`='$admin_id' AND `id` = '$value'";
$product_cateogry_details_query=mysqli_query($con,$product_cateogry_details);
$detail=mysqli_fetch_array($product_cateogry_details_query);
if ($last_key == $key) {
echo $detail['product_cateogry'];
}else{
echo $detail['product_cateogry']." , ";
}
}
$foods = [
'vegetables' => 'brinjal',
'fruits' => 'orange',
'drinks' => 'water'
];
$separateKeys = array_keys($foods);
$countedKeys = count($separateKeys);
for ($i = 0; $i < $countedKeys; $i++) {
if ($i == $countedKeys - 1) {
echo $foods[$separateKeys[$i]] . "";
} else {
echo $foods[$separateKeys[$i]] . ", \n";
}
}
Here $foods is my sample associative array.
I separated the keys of the array to count the keys.
Then by a for loop, I have printed the comma if it is not the last element and removed the comma if it is the last element by $countedKeys-1.