How to echo/print within a fuction with undefined variables in php? - php

I am not the best at php but currently I am trying to learn. I can print fine outside of the function but the specific instructions I have been given require me to print the results within the function. I have tried
echo "$area";
echo "calculatearea ()";
ive searched but still cant figure out how to get a print within the function only outside of it.
<?php
if (isset($_POST['CalcBT'])) {
global $area;
function calculateCircumference () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$circ = $num1 + $num2;
return $circ;
}
function calculateArea () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$area = 2*($num1 + $num2);
return $area;
}
echo "Your rectangle circumference is: " . calculateCircumference() . '<br />' . "Your rectangle area is: " . calculateArea();
}
?>
<!---------------- Form---------------->
<div class="form">
<h3></h3>
<form action="PHP-sida4.php" method="POST">
<p>Length: <input type="text" name="Length"value=""></p>
<p>Width: <input type="text" name="Width"value=""></p>
<input type="submit" name="CalcBT" value="Calculate">
</form>
I need the return value of $area along with what I echo'd in the bottom to actually print within the first function ( calculateCircumference )

You can echo anything you want within the function but it won't show up until you call the function.
<?php
if (isset($_POST['CalcBT'])) {
global $area;
function calculateCircumference () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$circ = $num1 + $num2;
// return $circ;
echo "Your rectangle circumference is: " . $circ . '<br />' . "Your rectangle area is: " . calculateArea();
return;
}
function calculateArea () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$area = 2*($num1 + $num2);
return $area;
}
calculateCircumference();
}
?>
I hope this helps!

Okay if am getting your question right, to need to return the area and some other text along with the area.
Let's begin with some house cleaning, therefore the $area global variable could be renamed to something else like $results Which will be an array or object. Taking it simple.
Lets go with an associative array where e.g:
$results = [
'area' => null,
'text' = null
];
From that your will be updating $results['area'] from the calculate function and also update the $results['text'] before calling echo, so probably extract the echoed text to another variable.
And now you can access $results anywhere within the file with both the area and the text:
To just be more expressive under CalculateArea() function do something like:
$results['area'] = $area;
Same thing with the echoed text.

You can use echo instead of return in your functions. To call them, your can just use function(); without any additional keyword :
function calculateCircumference () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$circ = $num1 + $num2;
echo $circ;
}
function calculateArea () {
$num1 = ($_POST['Length']);
$num2 = ($_POST['Width']);
$area = 2*($num1 + $num2);
echo $area;
}
echo "Your rectangle circumference is: " ;
calculateCircumference() ;
echo '<br />' ;
echo "Your rectangle area is: " ;
calculateArea();

You can echo anything anywhere, be it inside a function or outside of it. If an echo is not performing, then there was either an error, or the line where the echo can be found was not executed.
In our case you have removed the echo after your functions, which, coincidentally happened to be the only place where they were called.

Related

PHP objects and arrays

Hi I am new to PHP and I need to create an array and add both books to the array and than loop through the array this is where I am having trouble
if the price of a book is less than $20.00 output the book’s name and price
if the book’s title comes after the letter R in the alphabet output the book’s title.
My code so far is:
<?php
class Book {
// Properties
public $price;
public $title;
// Methods
function set_price($price) {
$this->price = $price;
}
function get_price() {
return $this->price;
}
function set_title($title) {
$this->title = $title;
}
function get_title() {
return $this->title;
}
}
$first_book = new Book();
$first_book->set_price('$13.95');
$first_book->set_title('Moby Dick');
echo "Price: " . $first_book->get_price();
echo "<br>";
echo "Title: " . $first_book->get_title();
echo "<br>";
$second_book = new Book();
$second_book->set_price('$23.99');
$second_book->set_title('Wuthering Heights');
echo "Price: " . $second_book->get_price();
echo "<br>";
echo "Title: " . $second_book->get_title();
echo "<br>";
$book = array("Moby Dick", "Wuthering Heights");
echo "Book Titles: " . $book[0] . ", " . " and " . $book[1] . ".";
?>
Kind Regurds
Kelly
Seems like you got most of it already, for the rest I would add a function to your Book class to get the first character of the title, and then use the ord (PHP documentation here) to convert it to an integer so you can check if it comes after the letter R.
<?php
// Add this to your Book class to get the first character of the title so we can check
// if the book comes after the letter 'R'
public function get_first_char() {
$titleArray = str_split($this->title);
return reset($titleArray);
}
// Instantiate your books and set properties ...
// Loop over each book
foreach ($book as $bookItem) {
$price = $bookItem->price;
// Right now $price is a string ('$xx.xx'), we need it to be numeric
$price = (float) substr($price, 1);
if ($price < 20) {
echo $bookItem->title;
echo $bookItem->price;
}
// Use the ord function to convert the ascii character into an int
if (ord(strtoupper($bookItem->get_first_char())) > ord('R')) {
echo $bookItem->title;
}
}
?>

Using PHP to print to HTML5 output tag

I am new to this. If I have some PHP code as in the example below, I can use the echo function to print the result. Echo always prints at the top of the screen. How do I format the tag so that in this case the result "$myPi" is printed to the screen using an HTML5 output tag? I am a newbie so please be kind to me and don't flame my post - I tried to format the code. Thanks QJB.
function taylorSeriesPi($Iteration)
{
$count = 0;
$myPi = 0.0;
for ($count=0; ($count<$Iteration);$count++)
{
if ( ($count%4) == 1)
{
$myPi = $myPi + (1/$count);
}
if ( ($count%4) == 3)
{
$myPi = $myPi - (1/$count);
}
}
$myPi *= 4.0;
echo ("Pi is ". $myPi. " After ".$Iteration. " iterations");
}
You can insert PHP anywhere in your document, and reference functions from any other place within the document or included files.
For example:
<?php
function taylorSeriesPi($Iteration)
{
$count = 0;
$myPi = 0.0;
for ($count=0; ($count<$Iteration);$count++)
{
...
}
$myPi *= 4.0;
// Return the value so we can use this function later.
return $myPi;
}
?>
<html>
<body>
<div id="somediv">
<?php
$iteration = 6/*or whatever*/;
echo "Pi is " . taylorSeriesPi($iteration) . " After " . $iteration . " iterations";
?>
</div>
</body>
</html>
This will put the returned value and associated string within the <div> tag, but you can put it anywhere in your HTML, as the output of the echo will simply be text by the time the markup is seen by your browser.

php Sum values returned from a while loop inside a function

I have written a function which returns a value from a while loop. I call this function 3 times and thus return 3 values. I want to sum these values. My function code is
<?php
function CalcTotal($Acc)
{
require('conn_bal.php');
$query = "SELECT Dte, SUM(Cred), SUM(Deb) FROM tbl_account WHERE Acc='$Acc'";
if ($result=mysqli_query($con,$query)) {
$TotBal = 0;
while($row = mysqli_fetch_array($result)){
global $scred, $sdeb;
$scred=$row['SUM(Cred)'];
$sdeb=$row['SUM(Deb)'];
$bal=$scred-$sdeb;
global $TotBal;
$TotBal = number_format($bal, 2);
return $TotBal;
}
}
}
?>
Which is called 3 different times i.e.
<?php
global $green;
$green = CalcTotal("Green");
echo $green;
echo "<br />";
global $blue;
$blue = CalcTotal("Blue");
echo $blue;
echo "<br />";
global $red;
$red = CalcTotal("Red");
echo $red;
echo "<br />";
?>
I then want to add these 3 returned values i.e.
<?php
global $Total;
$Total = $green + $blue + $red;
echo "Total: $Total";
?>
The correct values are being echoed but $Total = 3 The addition code is giving the count and is not summing the 3 returned variables.
I have tried all the permutations that I know and have researched this problem on the internet but to no avail.
If anyone has any ideas how I might achieve this I would be would be very grateful.
Many Thanks

PHP calculator increase

I am creating simple calculator. I am just learning php and this is a small project.I have created a calculator with two inputs but I am now testing it with just one. It works but only if you type number+number. It doesn't work if it is number+number+number.
I would like that it would work if you inputted 2+2+2... or 2*2*2... or 6-2-2... and 2/2/2...
Code:
// Create Variables
$y = $_POST["input1"];
// Echo input value on screen
echo "<p>Operation: " . $y . "</p>";
// Validation
if(empty($y)){
?>
<script>
$(document).ready(function(){
$('#error').append('Error: Your Input is empty');
});
</script>
<?php
}elseif(preg_match("/[a-zA-Z]/", $y)){
?>
<script>
$(document).ready(function(){
$('#error').append('Error: You can only input numbers');
});
</script>
<?php
}else{
// Calculation Brain FOR + Operator
if (strpos($y,'+') !== false) {
$omega = substr($y, 0, strpos($y, '+'));
$alpha = substr($y, strpos($y, '+') + 1);
echo "<p>Omega: " . $omega . "</p>";
echo "<p>Alpha: " . $alpha . "</p>";
$gamma = $omega + $alpha;
// The Sum FOR + operator
echo "Calculation: " . $gamma;
}
}
That's usually a bad practice, but here you can use eval. But you have first to check that your string doesn't contains disallowed characters.
$allowedCharacters = "0123456789./*-+()% ";
if(preg_match('/^[^'.preg_quote($allowedCharacters).']+$/'), $y) {
eval('$result = '.$y.';');
echo "Calculation: " . $result;
}
The only problem is that you'll not be able to handle errors.
you could use this for the same operation
$test='2+2*3';
eval('$calc = '.$test.';');
echo "Calculation: " . $calc;
the out should be : 8

pulling a random number into a symfony form

I am pulling two random numbers to create a math equation in a symfony form. The problem is when the form is submitted, the random numbers are updated, making the form submission invalid. How can I keep the initial number values loaded, so the form will process, but after successful process, load a new set?
actions.class
public function executeIndex(sfWebRequest $request)
{
$num1 = rand(0 , 20);
$num2 = rand(0 , 20);
$realAnswer = $num1 + $num2;
$show = $num1 . " + " . $num2 . " = ";
$this->getResponse()->setSlot("displayNum", $show);
$this->form = new UserForm();
echo $num1 . "<br>" . $num2 . "<br>" . $realAnswer;
if ($request->isMethod('post') && ($request->getPostParameter('captcha[answer]') == $realAnswer))
{
$this->processForm($request, $this->form);
}
}
I am using a partial to render the form -> _form.php
<tr height="40">
<td width="100" valign="middle">
<?php echo get_slot("displayNum", "default value if slot doesn't exist"); ?>
</td>
<td width="400" colspan="4" valign="middle">
<input type="text" id="captcha" class="url" name="captcha[answer]" style="width:100px" />
</td>
</tr>
Example: When the page initially loads, two random numbers are generated (ex. 10 & 15). This renders
10 + 15 = (input field)
The user inserts 25 and clicks save. This was correct, but because the form executes the index action again, there is a new set of random numbers making the "if" condition false.
UPDATE:
Per j0k's suggestion I have made the changes to the action.
public function executeIndex(sfWebRequest $request)
{
$user = $this->getUser();
if (!$request->isMethod('post'))
{
// first display of the form, generate nums
$num1 = rand(0 , 20);
$num2 = rand(0 , 20);
$realAnswer = $num1 + $num2;
// store them in session
$user->setAttribute('realAnswer', $realAnswer);
$user->setAttribute('num1', $num1);
$user->setAttribute('num2', $num2);
}
else
{
// the form is submitted, retrieve nums from the session
$num1 = $user->getAttribute('realAnswer', null);
$num2 = $user->getAttribute('num1', null);
$realAnswer = $user->getAttribute('num2', null);
}
//setup slot
$show = $num1 . " + " . $num2 . " = ";
echo $realAnswer . "-Actual<br>" . $request->getPostParameter('captcha[answer]') . "-User submitted";
$this->form = new UserForm();
if ($request->isMethod('post') && (($request->getPostParameter('captcha[answer]') == $realAnswer)))
{
$this->processForm($request, $this->form);
}
}
which should work. Looking at the variables, it looks like the page is pulling the session variable and not adding new random numbers on the second post. weird.
RESOLVED
It was a code error. I had the variables crossed up.
else
{
// the form is submitted, retrieve nums from the session
$num1 = $user->getAttribute('num1', null);
$num2 = $user->getAttribute('num2', null);
$realAnswer = $user->getAttribute('realAnswer', null);
../
Session is a good point.
If the form isn't posted, store the result in the session to be able to check it after.
public function executeIndex(sfWebRequest $request)
{
$user = $this->getUser();
if (! $request->isMethod('post'))
{
// first display of the form, generate nums
$num1 = rand(0 , 20);
$num2 = rand(0 , 20);
$realAnswer = $num1 + $num2;
// store them in session
$user->setAttribute('realAnswer', $realAnswer, 'captcha');
$user->setAttribute('num1', $num1, 'captcha');
$user->setAttribute('num2', $num2, 'captcha');
}
else
{
// the form is submitted, retrieve nums from the session
$num1 = $user->getAttribute('num1', null, 'captcha');
$num2 = $user->getAttribute('num2', null, 'captcha');
$realAnswer = $user->getAttribute('realAnswer', null, 'captcha');
}
$show = $num1 . " + " . $num2 . " = ";
$this->getResponse()->setSlot("displayNum", $show);
$this->form = new UserForm();
if ($request->isMethod('post') && ($request->getPostParameter('captcha[answer]') == $realAnswer))
{
$this->processForm($request, $this->form);
}
}
And don't forget to empty the related values in session if the form is valid.
protected function processForm(sfWebRequest $request, $form)
{
// bind form
if ($form->isValid())
{
// clear the session
$this->getUser()->getAttributeHolder()->removeNamespace('captcha');
}
}
Ps: if you are looking for a transparent captcha, I recommend you this method. I've tested it with really great success.
You could store the random numbers as session variables which will persist after reload:
session_start();
$_SESSION["num1"] = rand(0 , 20);
$_SESSION["num2"] = rand(0 , 20);

Categories