I would like to be able to output the name of a variable, along with that variable's value. My use case is something close to a debug situation, but I'm actually building a proof of concept for other developers and managers so we can talk about things like input filtering. Anyway...
The output HTML is currently a table, but that shouldn't matter. I can of course, just print out the name and then the contents in the HTML, but that gets tedious and is prone to typing errors. I'd like a function that I could call with the variable name, or a string with the variable name as the argument, and have that function generate the appropriate HTML for display. This doesn't appear to work.
This works:
<tr><td>$variable</td><td><?php print $variable?></td></tr>
This doesn't:
function rowFromVar($varname) {
$result = "<tr>";
$result .= "<td>\$$varname</td>";
$result .= "<td>" . $$varname . "</td>";
$result .= "</tr>";
return $result;
}
// now in the HTML...
<table><?php print rowFromVar("variable");?></table>
The variable variable $$varname is always empty. Notice that I'm passing in the name of the variable as a string, rather than trying to pass in the variable itself and work with it. I know that there be dragons that way. Instead, I'm trying to pass in the name of the variable as a string, and then use a variable variable (yeah, I know) to return the value of the original variable. That appears not to work either, and I'm betting it's a scope issue.
Is there any good way to accomplish what I'm looking for?
The variable variable $$varname is always empty. Notice that I'm
passing in the name of the variable as a string, rather than trying to
pass in the variable itself and work with it
It should be empty
Since you are passing variable as value, so:
$$varname
becomes:
$variable
and there is no value set for it.
In other words, you are just creating a variable with the name you pass as argument to function but you are not creating a value for it.
Solution:
This would work fine though if that's what you are looking to do:
function rowFromVar($varname) {
$result = "<tr>";
$result .= "<td>\$$varname</td>";
$result .= "<td>" . $varname . "</td>";
$result .= "</tr>";
return $result;
}
// now in the HTML...
<table><?php print rowFromVar("variable");?></table>
Simply remove $ from the variable on this line as done above:
$result .= "<td>" . $$varname . "</td>";
--------------------^
Did you try using $GLOBALS[$varname] instead of $$varname? Your variable in this example is at global scope, and you cannot directly access globals within a function.
You need declare your variable global within the function so that it references the global version. Adding this line at the start of your function should fix the problem:
function rowFromVar($varname) {
global $$varname;
$result = "<tr>";
$result .= "<td>\$$varname</td>";
$result .= "<td>" . $$varname . "</td>";
$result .= "</tr>";
return $result;
}
The following code should work, as you suspected scope is the main problem here.
function rowFromVar($varname, $contents) {
$result = "<tr>";
$result .= "<td>\$$varname</td>";
$result .= "<td>" . $contents . "</td>";
$result .= "</tr>";
return $result;
}
// now in the HTML...
<table><?php print rowFromVar("variable", $variable);?></table>
Please try this code:
function rowFromVar($varname) {
$result = "<tr>";
$result .= "<td>{$varname}</td>";
$result .= "<td>".$varname."</td>";
$result .= "</tr>";
return $result;
}
<table><?php echo rowFromVar("variable");?></table>
I had a similar problem, which I solved as follows.
function contents_of($string)
{
eval("global $string; \$value = $string;");
return "Variable $string has value $value";
}
$testing = 123;
echo contents_of('$testing');
// produces...
// Variable $testing has value 123
Related
I have multiple variables:
$Variable1 = '5/5/15';
$Variable2 = '6/13/76';
$Variable3 = '5/8/15';
...
I have an iteration variable:
$Iteration1 = 1;
while($Iteration1<=3){
echo "$Variable" . $Iteration1;
$Iteration1++;
}
desired result:
5/5/15
6/13/76
5/8/15
The Problem
Your current code echo "$Variable" . $Iteration1; tries to echo the value of the variable $Variable, which doesn't exist, and concatenate $Iteration1.
The Solution
What you want to do is build a string, "Variable" . $Iteration1 (e.g., $Variable2), then get the value of the variable with that name. This is called a "variable variable." You do this by writing ${string_you_want_to_create}, as in ${"Variable" . $Iteration1}.
Example Code For your Problem:
$Variable1 = '5/5/15';
$Variable2 = '6/13/76';
$Variable3 = '5/8/15';
$Iteration1 = 1;
while ($Iteration1 <= 3) {
echo ${"Variable" . $Iteration1} . "\n";
$Iteration1++;
}
Output:
5/5/15
6/13/76
5/8/15
Note: You could also do this in two steps, like this:
$variableName = "Variable" . $Iteration1;
echo $$variableName; // note the double $$
Try like this
echo ${"Variable" . $Iteration1};
Try this in loop
$var = 'Variable'.$Iteration1;
echo $$var.'<br>';
I'm generating dynamic content from a database like this:
$sql_select_items = $db->query("SELECT * FROM table WHERE ...);
Then it pulls the results, which may be one or multiple, like this:
while ($item_details = $db->fetch_array($sql_select_items))
{
$items_content =
'<table><tr> '.
'<td>RETRIEVED CONTENT HERE</td> '.
'</tr></table>';
}
Then, further down, I am outputting the generated content like this:
if ($section == 'summary_main')
{
$summary_page_content['content'] =
$summary_page_content['details'] .
$items_content .
$summary_page_content['messaging_received'] .
$summary_page_content['footer']
;
$template->set('members_area_page_content', $summary_page_content['content']);
}
Everything works except for the content generated by $items_content , which only displays 1 item no matter if there are 1 or 20. I tried to do a
$items_content . =
instead of
$items_content =
but that didn't seem to work either and just gave me an error.
What am I doing wrong?
It's not $db->fetch_array($sql_select_items) it's $sql_selected_items->fetch_array(). Here's how I would do it:
$table_rows = $db->query("SELECT * FROM table WHERE ...");
if($table_rows->num_rows > 0){
$table = '<table><tbody>';
while($row = $table_rows->fetch_object()){
$table .= "<tr><th>{$row->title_column_name}</th><td>{$row->other_column_name}</td></tr>";
}
$table .= '</tbody></table>';
}
else{
$table = '';
// no results
}
echo $table;
$table_rows->free(); $db->close();
Outside of (before) the while loop:
$items_content = '';
Inside the while loop:
$items_content .= '...';
This will make sure that your $items_content variable exists before your loop, and then the .= will concatenate your string to the end of $items_content.
"What am I doing wrong?"
As you didn't post the error, I can only assume you either got an undefined variable notice, which is solved by placing $items_content = ''; before the loop, or your got a syntax error because the operator you should be using is .= and not . = (note that the space is wrong).
First and foremost, forgive me if my language is off - I'm still learning how to both speak and write in programming languages. How I can retrieve an entire object from an array in PHP when that array has several key, value pairs?
<?php
$quotes = array();
$quotes[0] = array(
"quote" => "This is a great quote",
"attribution" => "Benjamin Franklin"
);
$quotes[1] = array(
"quote" => "This here is a really good quote",
"attribution" => "Theodore Roosevelt"
);
function get_random_quote($quote_id, $quote) {
$output = "";
$output = '<h1>' . $quote["quote"] . '.</h1>';
$output .= '<p>' . $quote["attribution"] . '</p>';
return $output;
} ?>
<?php
foreach($quotes as $quote_id => $quote) {
echo get_random_quote($quote_id, $quote);
} ?>
Using array_rand and var_dump I'm able to view the item in the browser in raw form, but I'm unable to actually figure out how to get each element to display in HTML.
$quote = $quotes;
$random_quote = array_rand($quote);
var_dump($quote[$random_quote]);
Thanks in advance for any help!
No need for that hefty function
$random=$quotes[array_rand($quotes)];
echo $random["quote"];
echo $random["attribution"];
Also, this is useless
<?php
foreach($quotes as $quote_id => $quote) {
echo get_random_quote($quote_id, $quote);
} ?>
If you have to run a loop over all the elements then why randomize hem in the first place? This is circular. You should just run the loop as many number of times as the quotes you need in output. If you however just need all the quotes but in a random order then that can simply be done in one line.
shuffle($quotes); // this will randomize your quotes order for loop
foreach($quotes as $qoute)
{
echo $quote["quote"];
echo $quote["attribution"];
}
This will also make sure that your quotes are not repeated, whereas your own solution and the other suggestions will still repeat your quotes randomly for any reasonably sized array of quotes.
A simpler version of your function would be
function get_random_quote(&$quotes)
{
$quote=$quotes[array_rand($quotes)];
return <<<HTML
<h1>{$quote["quote"]}</h1>
<p>{$quote["attribution"]}</p>
HTML;
}
function should be like this
function get_random_quote($quote_id, $quote) {
$m = 0;
$n = sizeof($quote)-1;
$i= rand($m, $n);
$output = "";
$output = '<h1>' . $quote[$i]["quote"] . '.</h1>';
$output .= '<p>' . $quote[$i]["attribution"] . '</p>';
return $output;
}
However you are not using your first parameter-$quote_id in the function. you can remove it. and call function with single parameter that is array $quote
Why don't you try this:
$quote = $quotes;
$random_quote = array_rand($quote);
$random = $quote[$random_quote];
echo '<h1>' . $random["quote"] . '.</h1><br>';
echo '<p>' . $random["attribution"] . '</p>';
Want to create a function:
echo get_random_quote($quotes);
function get_random_quote($quotes) {
$quote = $quotes;
$random_quote = array_rand($quote);
$random = $quote[$random_quote];
return '<h1>' . $random["quote"] . '.</h1><br>'.'<p>' . $random["attribution"] . '</p>';
}
First, you dont need the $quote_id in get_random_quote(), should be like this:
function get_random_quote($quote) {
$output = "";
$output = '<h1>' . $quote["quote"] . '.</h1>';
$output .= '<p>' . $quote["attribution"] . '</p>';
return $output;
}
And I cant see anything random that the function is doing. You are just iterating through the array:
foreach($quotes as $quote_id => $quote) {
echo get_random_quote( $quote);
}
According to http://php.net/manual/en/function.array-rand.php:
array_rand() Picks one or more random entries out of an array, and
returns the key (or keys) of the random entries.
So I guess $quote[$random_quote] should return your element, you can use it like:
$random_quote = array_rand($quotes);
echo get_random_quote($quote[$random_quote]);
I need the array($project_Ids) out of function any suggestion.This is in view
I can't call the function cause already is called; I just want some how to update this array().
$project_Ids=array();
function generateProperties($listP, $sizeS){
global $project_Ids;
$i=0;
foreach ($listP as $pr) {
$i++;
$pr['project_id'];
$project_Ids[$i]=$pr['project_id'];
echo "<li class='' style='cursor: pointer;height:" . $sizeSmallBlock . "px;' dds='" . $project['project_id'] . '-' . $project['project_calendar_id'] . "' id='" . $project['project_id'] . '-' . $project['project_calendar_id'] . "'>" .
$description .
"</li>";
}
}
You need to define the array inside the function, and then have the function return it!
function generateProperties($listP, $sizeS){
$project_Ids=array();
$i=0;
foreach ($listP as $pr) {
$i++;
$project_Ids[$i]=$pr['project_id'];
}
return $project_Ids;
}
// then elsewhere in your code
$project_Ids = generateProperties($listP, $sizeS);
Edit:
From looking at your foreach loop - it seems you are just getting the array values and storing them in an array? If so - just use array_values - it does exactly what you want in one line of code:
$project_Ids = array_values($listP);
It is already available outside of the function, as you have correctly defined it outside.
You may want to brush up on scope.
$project_Ids = generateProperties($listP, $sizeS);
This will work but you have to read it from end of the page after rendering all the page :)
So I am using Codeignitor and I am trying to figure out the best way to share my constants with my javascript in a neat maintainable way.
1) in the view I could echo out my variables in like my footer (yuuuck!)
2) I could parse a partial view which contains a template for javascript and inject that in my view (maybe?)
3) I could dynamically create a javascript file like myJavascript.js.php and include that in my header.
What's the best maintainable way to implement PHP into JS in a MVC framework?
To keep my variables nicely wrapped I use a JSON object - that way I won't incur in issues with encoding, slashes, having to manually update the JavaScript every variable I add...
$variables_to_view['js_variables']['var_name'] = $var_name;
then pass it to the view
php_variables = <?php echo json_encode($js_variables) ?>;
alert(php_variables.var_name);
There doesn't seem to be anything wrong about echoing your variables in the script tag. In fact, frameworks like BackboneJS are encouraging you to do so for data you need to pass to your client-side code.
You can use short tag like this:
For Example:
You want to use $abc variable in js, then you will need to write this in js
var abc = <?=$abc?>;
You can create php file .
Something like script.js.php?outfor=1;
<?php
header("Content-type:text/javascript"); //can be application/javascript.
?>
ABC = <?php echo $abc?>
CBA = <?php echo $cba?>
BAC = <?php echo $bac?> //and so on.
Some additional info .
If you use "var" in function that variable will be visible only in that function and without "var"means global.
So.
function abc()
{
var a = 1; //only in abc()
b=2; //global
}
I know that in terms of programming skills it's not the best, but finally it's what I use and it's working. To make it short: I put all my constants in a xml file and I have this little script that generates two separate files with the same content, but different syntax. I am just pasting the code with my values. If it's useful for anybody, I'll be very happy to help.
The xml is the simplest possible; value
<?php
define("GECOXML_PATH","../xml/geco.xml");
define("PHP_GECO_FN","../.includes/geco.php");
define("JS_GECO_FN","../js/geco.js");
echo "******** GECO (GEnerate COnstants files for PHP and JS) **********<br>";
echo "<br>";
echo " input xml file: ". GECOXML_PATH."<br>";
echo " output php file: ". PHP_GECO_FN."<br>";
echo " output js file: ". JS_GECO_FN."<br>";
echo "********************************************************************<br>";
$geco = (object)xmlParse(GECOXML_PATH);
echo "<br>";
echo "<br>";
echo "************ PHP GECO ************* <br>";
echo "<br>";
$PHP = gecoPHP($geco);
echo "<br>";
echo "<br>";
echo "************** JS GECO ************<br>";
echo "<br>";
$JS = gecoJS($geco);
writeFiles($PHP, $JS);
//****** Functions *********
function xmlParse ($url) {
$fileContents= file_get_contents($url);
$fileContents = str_replace(array("\n", "\r", "\t"), '', $fileContents);
$fileContents = trim(str_replace('"', "'", $fileContents));
return simplexml_load_string($fileContents);
}
function writeFiles($PHPcontent, $JScontent)
{
echo "<br> PhP ok:". file_put_contents(PHP_GECO_FN, $PHPcontent) . "<br>";
echo "<br> JS ok:" . file_put_contents(JS_GECO_FN, $JScontent) . "<br>";
}
function gecoPHP($gecoOBJ)
{
foreach ($gecoOBJ as $key => $value)
{
if (is_numeric(str_replace(" ","",$value)))
{
$line = "define(\"" . $key . "\",". intval($value) . ");\n";
}
else
{
$line = "define(\"" . $key . "\",\"". $value . "\");\n";
}
$phpContent = $phpContent . $line;
echo $line."<br>";
}
return "<?php\n"$phpContent."?>";
}
function gecoJS($gecoOBJ)
{
foreach ($gecoOBJ as $key => $value)
{
if (is_numeric(str_replace(" ","",$value)))
{
$line = "var " . $key . "=". $value . ";\n";
}
else
{
$line = "var " . $key . "=\"". $value . "\";\n";
}
$JSContent = $JSContent . $line;
echo $line."<br>";
}
return $JSContent;
}
?>