Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

PHP code in a string variable 3

Status
Not open for further replies.

maharg

Technical User
Mar 21, 2002
184
0
0
Hi,

I am trying to create a string variable with some php code in it , which will be used multiple times in a document. This is so if I want to edit that code, I only need edit that one variable.

For example, I would simply like to put the following code snippet...

Code:
fprintf('%01.2f', $price)

... into a variable called $poundsformat, which I will then introduce in the script with echo $format.

The array will be in an include file and will be much larger than this example.

I am getting parse errors, which didn't surprise me, but I have been unable to find a solution. I tried HEREDOC, EOD, EOT, double quotes, curly braces etc!

Any help would be much appreciated!

Many thanks,

Graham


Here is an example of the code I am testing with....

Code:
<html>
<head>
</head>
<body>

<?php
// Currency format, rounded and force 2 decimal places if whole numbers
$poundsformat =   fprintf('%01.2f', $price) ;


// Exchange rates
$pounds=1;
$euros=1.1397.
$usdollars=1.5602;
$cdndollars=1.5769;


// Prices arrays 
$prices = array ( 

"intuitive" => array 
( 
"INT2-AH" => "173",
"INT2-C"  => "168",
"INT2-L"  => "173",
"INT2-P"  => "142",
"INT2-S2" => "163",
"INT2-S4" => "184",
"INT2-H"  => "170",	
"INT2-R"  => "163",	
"INT-T"   => "125",		
"INT2-I"  => "157",	
),

"tester" => array 
( 
"ABC" => "400",
"DEF"  => "887",
),

);
?>


<table width=800>
<tr> <th style="text-align:left">Part No.</th> <th style="text-align:left">Description</th><th style="text-align:left">GB Pounds</th><th style="text-align:left">Euros</th><th style="text-align:left">US Dollars</th><th style="text-align:left">Cdn Dollars</th><th>Group</th></tr>
<tr><td>INT2-AH</td><td>Ampere hour meter</td><td><?php $price=($prices["intuitive"]["INT2-AH"]); echo $poundsformat ?></td><td><?php echo sprintf("%01.2f", round(($euros* $price),2)); ?></td><td><?php echo  sprintf("%01.2f", round(($usdollars* $price),2)); ?></td><td><?php echo     sprintf("%01.2f", round(($cdndollars* $price),2)); ?></td><td bgcolor="blue"> </td></tr>
<tr><td>INT2-C</td><td>Totaliser/Rate meter</td><td><?php $price=($prices["intuitive"]["INT2-C"]); echo sprintf("%01.2f", $price); ?></td><td><?php echo sprintf("%01.2f", round(($euros* $price),2)); ?></td><td><?php echo  sprintf("%01.2f", round(($usdollars* $price),2)); ?></td><td><?php echo  sprintf("%01.2f", round(($cdndollars* $price),2)); ?></td><td bgcolor="blue"> </td></tr>
<tr><td>INT2-P</td><td>Process meter</td>         <td><?php $price=($prices["intuitive"]["INT2-P"]); echo sprintf("%01.2f", $price); ?></td><td><?php echo sprintf("%01.2f", round(($euros* $price),2)); ?></td><td><?php echo  sprintf("%01.2f", round(($usdollars* $price),2)); ?></td><td><?php echo  sprintf("%01.2f", round(($cdndollars* $price),2)); ?></td><td bgcolor="blue"> </td></tr>
</table>
</body>
</html>







 
this line is incorrect
Code:
$euros=1.1397.

the dot is used in php as a concatenator. lines must be terminated with a semicolon.

I cannot see the point of this line
Code:
$poundsformat =   fprintf('%01.2f', $price) ;

fprintf() sends a formatted string down a stream. This will also error as you are not providing a stream resource reference as a first argument.

if you want to store a result in a variable as a string, use sprintf().

other than that, I see no php syntax errors in your code.
 
I am trying to create a string variable with some php code in it , which will be used multiple times in a document

I'm not sure if that makes as much sense as you think it does.

Anyway, if you want to have PHP code in a variable and then have it be executed somewhere, you'll need to insert it into the variable as a string, and then use eval() to run the code.

Perhaps what you really want is a function?

Code:
function formatValue($value){
return sprintf('%01.2f', $value);
}

....

echo formatValue(round(($usdollars* $price),2));

}



This will format the result of the round function according to your parameters.

You can go even further and pass the formatting as an additional parameter so you can change it as needed.



----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
Hi guys, thanks for that, I don't think I explained myself clearly enough.

Here is a code which works, but which I want to simplify - the actual values for $price will come from an array...

Code:
<html>
<head>
<style type="text/css" media="screen">@import "[URL unfurl="true"]http://www.london-electronics.com/lel.css";</style>[/URL]
<style type="text/css" media="print">@import "[URL unfurl="true"]http://www.london-electronics.com/lel_noprint.css";</style>[/URL]
</head>
<body>
<center>

<?php
$pounds=1;
$euros=1.1397;
$usdollars=1.5602;
$cdndollars=1.5769;
?>

<table width=800>
<tr> <th style="text-align:left">Part No.</th><th style="text-align:left">Description</th><th style="text-align:left">GB Pounds</th><th style="text-align:left">Euros</th><th style="text-align:left">US Dollars</th><th style="text-align:left">Cdn Dollars</th><th style="text-align:left">Group</th></tr>
<tr><td>INT2-AH</td><td>Ampere hour meter</td><td><?php $price=100;             echo sprintf("%01.2f", $price); ?></td><td><?php echo sprintf("%01.2f", ($euros* $price)); ?></td><td><?php echo  sprintf("%01.2f", ($usdollars* $price)); ?></td><td><?php echo  sprintf("%01.2f", ($cdndollars* $price)); ?></td><td ><img src="blue.gif" title="Blue"  alt="Blue"><td></tr>
<tr><td>INT2-C</td><td>Totaliser/Rate meter</td><td><?php $price=120;               echo sprintf("%01.2f", $price); ?></td><td><?php echo sprintf("%01.2f", ($euros* $price)); ?></td><td><?php echo  sprintf("%01.2f", ($usdollars* $price)); ?></td><td><?php echo  sprintf("%01.2f", ($cdndollars* $price)); ?></td><td><img src="green.gif" title="Green" alt="Green"></td></tr>
<tr><td>INT2-P</td><td>Process meter</td><td><?php $price=170;                        echo sprintf("%01.2f", $price); ?></td><td><?php echo sprintf("%01.2f", ($euros* $price)); ?></td><td><?php echo  sprintf("%01.2f", ($usdollars* $price)); ?></td><td><?php echo  sprintf("%01.2f", ($cdndollars* $price)); ?></td><td><img src="red.gif" title="Red" alt="Red"></td></tr>
</table>

</center>
</body>
</html>

As you can see, after the $value=100; there is a lot of 'material' which is repeated on each line.

I may have 1000 lines of different items and prices, so I wanted to put all the code you see to the right of the price in a single reusable string, which would make maintenance easier.

So I was aiming for something like ...

Code:
<html>
<head>
<style type="text/css" media="screen">@import "[URL unfurl="true"]http://www.london-electronics.com/lel.css";</style>[/URL]
<style type="text/css" media="print">@import "[URL unfurl="true"]http://www.london-electronics.com/lel_noprint.css";</style>[/URL]
</head>
<body>
<center>

<?php
$pounds=1;
$euros=1.1397;
$usdollars=1.5602;
$cdndollars=1.5769;

// This is the bit I am struggleing with...
$condensed= "echo sprintf("%01.2f", $price); ?></td><td><?php echo sprintf("%01.2f", ($euros* $price)); ?></td><td><?php echo  sprintf("%01.2f", ($usdollars* $price)); ?></td><td><?php echo  sprintf("%01.2f", ($cdndollars* $price)); ?></td><td><img src="red.gif" title="Red" alt="Red"></td></tr>";
?>

<table width=800>
<tr> <th style="text-align:left">Part No.</th><th style="text-align:left">Description</th><th style="text-align:left">GB Pounds</th><th style="text-align:left">Euros</th><th style="text-align:left">US Dollars</th><th style="text-align:left">Cdn Dollars</th><th style="text-align:left">Group</th></tr>
<tr><td>INT2-AH</td><td>Ampere hour meter</td><td><?php $price=100; echo $condensed;?>          
<tr><td>INT2-C</td><td>Totaliser/Rate meter</td><td><?php $price=120;   echo $condensed;?>         
<tr><td>INT2-P</td><td>Process meter</td><td><?php $price=170;             echo $condensed;?>             
</table>

</center>
</body>
</html>

Hoping that makes it a little clearer.

Thanks again,

Graham
 
I hope this is taken as a legitimate question, because I've never seen this done quite this way. What does "echo sprintf()" do that "printf()" doesn't do in this case. My first thought would be:

Code:
$format = '%01.02f';
printf($format, $euros * $price);

Or, I might create a function to do it:

Code:
function FormatPrice($price)
{
    $format = '%01.2f';
    $conversions = array(
        'eur' => 1.1397,
        'usd' => 1.5602,
        'cdn' => 1.5769,
    );
    $retval = '';

    foreach ($conversions as $cname => $cvalue) {
        $retval .= '<td>' . sprintf($format, $price * $cvalue) . '</td>';
    }
    return $retval;
}

Then...
Code:
<tr><td>INT2-AH</td><td>Ampere hour meter</td><?php echo FormatPrice(100);?></tr>
I just kept the conversion as name=>value so later updates would be simple. That changes often and maybe should be constants defined at the top of the file.
 
Echoing PHP commands as you are showing will never work.
Again you would need to use the eval function to run the PHP commands which exist inside a string.

What you want is a function as has been said.

Code:
...
function Condensed($price){
$pounds=1;
$euros=1.1397;
$usdollars=1.5602;
$cdndollars=1.5769;

return  sprintf("%01.2f", $price) . "</td><td>" . sprintf("%01.2f", ($euros* $price)) . "</td><td> " . sprintf("%01.2f", ($usdollars* $price)) . "</td><td>" .  sprintf("%01.2f", ($cdndollars* $price)) . '</td><td><img src="red.gif" title="Red" alt="Red"></td></tr>';

}
?>

<table width=800>
<tr> <th style="text-align:left">Part No.</th><th style="text-align:left">Description</th><th style="text-align:left">GB Pounds</th><th style="text-align:left">Euros</th><th style="text-align:left">US Dollars</th><th style="text-align:left">Cdn Dollars</th><th style="text-align:left">Group</th></tr>
<tr><td>INT2-AH</td><td>Ampere hour meter</td><td><?php $price=100; echo Condensed($price);?>          
<tr><td>INT2-C</td><td>Totaliser/Rate meter</td><td><?php $price=120;   echo Condensed($price);?>         
<tr><td>INT2-P</td><td>Process meter</td><td><?php $price=170;             echo Condensed($price);?>             
</table>


</body>
</html>






----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
Thanks guys - function added and all working exactly as hoped for - much apreciated!
 
Vacunita said:
Echoing PHP commands as you are showing will never work.

am I missing something? why would not this work: (?)
Code:
echo sprintf('some format', $somevariable);

(I agree it is unnecessary over printf.)
 
That works, doing:
Code:
$condensed= "[green]echo sprintf("%01.2f", $price); ?></td><td><?php echo sprintf("%01.2f", ($euros* $price)); ?></td><td><?php echo  sprintf("%01.2f", ($usdollars* $price)); ?></td><td><?php echo  sprintf("%01.2f", ($cdndollars* $price)); ?></td><td><img src="red.gif" title="Red" alt="Red"></td></tr>[/green]";

and then simply:

echo $condensed;

[b]does not[/b]

Ignoring the other double quotes and other syntax errors it may have. wrapping a php command in a string renders the commands unuseable unless eval is used. It would simply output the PHP code as text, but it won't run it.



----------------------------------
Phil AKA Vacunita
----------------------------------
Ignorance is not necessarily Bliss, case in point:
Unknown has caused an Unknown Error on Unknown and must be shutdown to prevent damage to Unknown.

Web & Tech
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top