Where does the additional 0 come from - php

I have been a developer for more than 5 years but this seems to be confusing and strange. I tried to use two functions having echo on each function. Then, I call those functions and echoed again. Why does this code below displays 5100 instead of 510 only? Where does the additional 0 come from?
<?php
function firstNum()
{
echo 5;
}
function secondNum()
{
echo 10;
}
echo firstNum() + secondNum(); //Output is 5100

Your code is echoing 5 then 10 then the sum of null plus null.
When you don't use a return php will return null from the function call.
You mean to do this: (Demo)
function firstNum()
{
return 5;
}
function secondNum()
{
return 10;
}
echo firstNum() + secondNum(); //Output is 15
You can remove the echos in the function to have a better understanding of what is returned: (Demo)
function firstNum()
{
//echo 5;
}
function secondNum()
{
//echo 10;
}
var_export(firstNum());
echo "\n";
var_export(secondNum());
echo "\n";
var_export(null+null);
Output:
NULL
NULL
0

Related

php loop flip coin until 2 heads, then stop

I'm new to php and am trying to write a loop that will flip a coin until exactly two heads have been flipped and then stop.
So far I've written a function for coin flipping:
function cointoss () {
$cointoss = mt_rand(0,1);
$headsimg = '<img src=""/>';
$tailsimg = '<img src=""/>';
if ($cointoss == 1){
print $headsimg;
} else {
print $tailsimg;
}
return $cointoss;
}
...but am stuck on writing the loop. I've tried a couple ways:
#this code takes forever to load
$twoheads = 0;
for ($twoheads = 1 ; $twoheads <= 20; $twoheads++) {
$cointoss = mt_rand(0,1);
cointoss ();
if ($cointoss == 1) {
do {
cointoss ();
} while ($cointoss == 1);
}
}
#one coin flips
do {
cointoss ();
} while ($cointoss == 1);
This is a for a class, and we haven't learned arrays yet, so I need to accomplish this without them.
I understand the concept of loops executing code while a condition is true, but don't understand how to write for when a condition is no longer true.
Printing from inside of "processing functions" is a bad habit to get into. You might like to declare a showCoin($toss) function for printing. In truth, I don't know if I would bother with any custom functions.
You need to declare a variable which will hold the return value from your function.
By storing the current and previous toss values, you can write a simple check if two consecutive "heads" have occurred.
Code: (Demo)
function cointoss () {
return mt_rand(0,1); // return zero or one
}
$previous_toss = null;
$toss = null;
do {
if ($toss !== null) { // only store a new "previous_toss" if not the first iteration
$previous_toss = $toss; // store last ieration's value
}
$toss = cointoss(); // get current iteration's value
echo ($toss ? '<img src="heads.jpg"/>' : '<img src="tails.jpg"/>') , "\n";
// ^^^^^- if a non-zero/non-falsey value, it is heads, else tails
} while ($previous_toss + $toss != 2);
// ^^^^^^^^^^^^^^^^^^^^^^- if 1 + 1 then 2 breaks the loop
Possible Output:
<img src="heads.jpg"/>
<img src="tails.jpg"/>
<img src="tails.jpg"/>
<img src="tails.jpg"/>
<img src="heads.jpg"/>
<img src="heads.jpg"/>

Function doesn't save variable

I'm trying to add 1 to a number each time a function is called, but for some reason, the total number is always same.
Here is my current code:
<?php
$total;
function draw_card() {
global $total;
$total=$total+1;
echo $total;
}
draw_card();
draw_card();
?>
Personally, I would not use globals, but if I was forced at gunpoint I would handle state within the function, so outside variables did not pollute the value. I would also make an arbitrary long key name which I would not use anywhere else.
<?php
function draw_card($initial = 0) {
$GLOBALS['draw_card_total'] = (
isset($GLOBALS['draw_card_total']) ? $GLOBALS['draw_card_total']+1 : $initial
);
return $GLOBALS['draw_card_total'];
}
// optionally set your start value
echo draw_card(1); // 1
echo draw_card(); // 2
https://3v4l.org/pinSi
But I would more likely go with a class, which holds state by default, plus its more verbose as to whats happening.
<?php
class cards {
public $total = 0;
public function __construct($initial = 0)
{
$this->total = $initial;
}
public function draw()
{
return ++$this->total;
}
public function getTotal()
{
return $this->total;
}
}
$cards = new cards();
echo $cards->draw(); // 1
echo $cards->draw(); // 2
echo $cards->getTotal(); // 2
https://3v4l.org/lfbcL
Since it is global already, you can use it outside the function.
<?php
$total;
function draw_card() {
global $total;
$total=$total+1;
//echo $total;
}
draw_card();
draw_card();
draw_card();
echo "Current Count :", $total;
?>
Result :
Current Count :3
This will increment the number of times you call the function.
Since you echoed the result/total each time without a delimiter, you might have considered the output to be 12(Assumption)
Functions have a scope.. you just need to bring $total into the scope of the function... best to not do it globally but as an argument.
$total = 0;
function draw_card($total) {
return $total + 1;
}
$total = draw_card($total);
//Expected Output = 1
$total = draw_card($total);
//Expected Output = 2

Is there any possibility to break a loop while calling a function?

Let's say I have a simple code:
while(1) {
myend();
}
function myend() {
echo rand(0,10);
echo "<br>";
if(rand(0,10) < 3) break;
}
This will not work with error code 'Fatal error: Cannot break/continue 1 level on line'.
So is there any possibility to terminate the loop during a subfunctin execution?
Make the loop condition depend upon the return value of the function:
$continue = true;
while( $continue) {
$continue = myend();
}
Then, change your function to be something like:
function myend() {
echo rand(0,10);
echo "<br>";
return (rand(0,10) < 3) ? false : true;
}
There isn't. Not should there be; if your function is called somewhere where you're not in a loop, your code will stop dead. In the example above, your calling code should check the return of the function and then decide whether to stop looping itself. For example:
while(1) {
if (myend())
break;
}
function myend() {
echo rand(0,10);
echo "<br>";
return rand(0,10) < 3;
}
Use:
$cond = true;
while($cond) {
$cond = myend();
}
function myend() {
echo rand(0,10);
echo "<br>";
if(rand(0,10) < 3) return false;
}

Calculate number of squares from a rectangle

I'm working on some PHP code but I'm stuck with a logic.
I need to find out the number of squares from a rectangle.
I'm unable to implement this in PHP.
Please help.
I tried this:
function getcount($length,$breadth,$count=0){
$min=min($length,$breadth);
if($length>$breadth){
$length=$length-$min;
$count++;
return getcount($length,$breadth,$count);
}
else if($breadth>$length){
$breadth=$breadth-$min;
$count++;
return getcount($length,$breadth,$count);
}
else{
$count+=($length/$min);
}
return $count;
}
But some how it doesn't pass all the use cases.
And i do not know on which use cases, it fails?
I think the easiest way to calculate the number of squares in a rectangle is to substract the found squares from it while it disappears completely.
It works fine for me:
function getcount($width,$height) {
$total=0;
while($width && $height)
{
if($width>$height)
{
$width-=$height;
}
else if($height>$width)
{
$height-=$width;
}
else
{
$width=0;
$height=0;
}
$total+=1;
}
return $total;
}
echo getcount(5,3)."<br/>";
echo getcount(5,5)."<br/>";
echo getcount(11,5)."<br/>";
Output:
4
1
7
In my opinion there is nothing wrong in your code. The output from the code in OP is exactly the same as the output of the code in the accepted answer. You can run this (where getcount() is the function from OP and getcount2() is the function from the Balázs Varga's answer):
for ($i=0; $i<10000; $i++)
{
$a=mt_rand(1,50);
$b=mt_rand(1,50);
$r1 = getcount($a, $b);
$r2 = getcount2($b, $b);
if ($r1 != $r2)
{
echo "D'oh!";
}
}
and it will not return anything at all.
The only flaw is your code will throw a warning message when you run getcount(0, 0).
Also, the second line in your code ($min=min($length,$breadth);) is a bit redundant. You can write the same this way:
function getcount($length,$breadth,$count=0){
if($length>$breadth){
$length=$length-$breadth;
$count++;
return getcount($length,$breadth,$count);
}
else if($breadth>$length){
$breadth=$breadth-$length;
$count++;
return getcount($length,$breadth,$count);
}
else if ($breadth!=0){
$count++; // there is no need to divide two same numbers, right?
}
return $count;
}

Detecting negative numbers

I was wondering if there is any way to detect if a number is negative in PHP?
I have the following code:
$profitloss = $result->date_sold_price - $result->date_bought_price;
I need to find out if $profitloss is negative and if it is, I need to echo out that it is.
if ($profitloss < 0)
{
echo "The profitloss is negative";
}
Edit: I feel like this was too simple an answer for the rep so here's something that you may also find helpful.
In PHP we can find the absolute value of an integer by using the abs() function. For example if I were trying to work out the difference between two figures I could do this:
$turnover = 10000;
$overheads = 12500;
$difference = abs($turnover-$overheads);
echo "The Difference is ".$difference;
This would produce The Difference is 2500.
I believe this is what you were looking for:
class Expression {
protected $expression;
protected $result;
public function __construct($expression) {
$this->expression = $expression;
}
public function evaluate() {
$this->result = eval("return ".$this->expression.";");
return $this;
}
public function getResult() {
return $this->result;
}
}
class NegativeFinder {
protected $expressionObj;
public function __construct(Expression $expressionObj) {
$this->expressionObj = $expressionObj;
}
public function isItNegative() {
$result = $this->expressionObj->evaluate()->getResult();
if($this->hasMinusSign($result)) {
return true;
} else {
return false;
}
}
protected function hasMinusSign($value) {
return (substr(strval($value), 0, 1) == "-");
}
}
Usage:
$soldPrice = 1;
$boughtPrice = 2;
$negativeFinderObj = new NegativeFinder(new Expression("$soldPrice - $boughtPrice"));
echo ($negativeFinderObj->isItNegative()) ? "It is negative!" : "It is not negative :(";
Do however note that eval is a dangerous function, therefore use it only if you really, really need to find out if a number is negative.
:-)
if(x < 0)
if(abs(x) != x)
if(substr(strval(x), 0, 1) == "-")
You could check if $profitloss < 0
if ($profitloss < 0):
echo "Less than 0\n";
endif;
if ( $profitloss < 0 ) {
echo "negative";
};
Don't get me wrong, but you can do this way ;)
function nagitive_check($value){
if (isset($value)){
if (substr(strval($value), 0, 1) == "-"){
return 'It is negative<br>';
} else {
return 'It is not negative!<br>';
}
}
}
Output:
echo nagitive_check(-100); // It is negative
echo nagitive_check(200); // It is not negative!
echo nagitive_check(200-300); // It is negative
echo nagitive_check(200-300+1000); // It is not negative!
Just multiply the number by -1 and check if the result is positive.
You could use a ternary operator like this one, to make it a one liner.
echo ($profitloss < 0) ? 'false' : 'true';
I assume that the main idea is to find if number is negative and display it in correct format.
For those who use PHP5.3 might be interested in using Number Formatter Class - http://php.net/manual/en/class.numberformatter.php. This function, as well as range of other useful things, can format your number.
$profitLoss = 25000 - 55000;
$a= new \NumberFormatter("en-UK", \NumberFormatter::CURRENCY);
$a->formatCurrency($profitLoss, 'EUR');
// would display (€30,000.00)
Here also a reference to why brackets are used for negative numbers:
http://www.open.edu/openlearn/money-management/introduction-bookkeeping-and-accounting/content-section-1.7
Can be easily achieved with a ternary operator.
$is_negative = $profitloss < 0 ? true : false;
I wrote a Helper function for my Laravel project but can be used anywhere.
function isNegative($value){
if(isset($value)) {
if ((int)$value > 0) {
return false;
}
return (int)$value < 0 && substr(strval($value), 0, 1) === "-";
}
}

Categories