This question already has answers here:
How exactly does if($variable) work? [duplicate]
(8 answers)
Closed 7 years ago.
This is the code
<p>We are going to flip a coin until we get three heads in a row!</p>
<?php
$headCount = 0;
$flipCount = 0;
while ($headCount < 3) {
$flip = rand(0, 1);
$flipCount ++;
if ($flip) {
$headCount ++;
echo "<div class=\"coin\">H</div>";
} else {
$headCount = 0;
echo "<div class=\"coin\">T</div>";
}
}
echo "<p>It took {$flipCount} flips!</p>";
?>
I've played around with Java but I'm now learning PHP. The part that doesn't make sense right here is this.
if ($flip) {
$headCount ++;
echo "<div class=\"coin\">H</div>";
}
What exactly is being checked here? I doubt it's checking whether $flip is true.
It's a common shorthand in these kinds of languages. Once you get used to it, it seems natural.
In this case,
if ($flip)
is equivalent to:
if ($flip == 1)
But PHP is really just checking for a "truthy" value: true, not zero, not "0" or "", not [], and others will evaluate as true and pass the if ($flip) test.
Related
This question already has answers here:
The 3 different equals
(5 answers)
Closed 3 years ago.
Summary: Trying to add +1 each time I go through my foreach loop, but it keeps going up even though I would only expect a maximum of 11 results in the loop
I tried to move around on the $i++; but without luck, I also check that I made sure the $i = 0; was outside of the foreach loop.
<?php
$facade = new NewsArticleFacade();
$news = $facade->getAll();
unset($facade);
$i = 0;
foreach($news as $new)
{
$i++;
if ($i = 5000000000000000)
{
echo "if statement: " . $i;
break;
}
$content = substr($new->getContent(), 0, 69);
echo "<div class='news'>";
echo "<h4><a href='/news/news.php?id=".$new->getNewsID()."'>".$new->getTitle()."</a></h4>";
echo "<span>by <a href='#'>".$new->getUser()->getUsername()."</a> - ".$new->getDate()->format("d-M-Y")."</span>";
echo "<p>".$content." ...</p>";
echo "<div class='gradient'></div>";
echo "<img src='img/news/0000000001.jpg'>";
echo "</div>";
}
?>
What really confuses me is if I remove the if statement for the loop, and just echo $i each time, it will echo out 11 in total, what am i doing wrong with my if?
I would expect the loop to go through 11 times since I have 11 entries in the database for this selection, but it keeps going up, if I echo within the if statement i can see the value will just be whatever i limit the if statement to be.
Thanks in advance!
This
if ($i = 5000000000000000)
Is assignment and it makes little sense as such in your code. You probably wanted to have comparison operation which is expressed with ==
if ($i == 5000000000000000)
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I was in a job interview and was asked to solve FizzBuzz with PHP.
Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.
I never heard of FizzBuzz before but here is how I solved it because I didn't know modulo or how to use it.:
for ($i = 1; $i <= 100; $i++){
if($i / 3 == round($i / 3) && $i / 5 == round($i / 5)){
echo $i . " is FizzBuzz<br />";
}
else if($i / 3 == round($i / 3)){
echo $i . " is Fizz<br />";
}
else if($i / 5 == round($i / 5)){
echo $i . " is Buzz<br />";
}
else {
echo $i."<br />";
}
}
I googled and didn't find any solution with round and that got me thinking that maybe there is something wrong with it, this is one of the solutions I found that is close to mine:
for ($i = 1; $i <= 100; $i++){
if($i % 3 == 0 && $i % 5 ==0){
echo "FizzBuzz<br />";
}
else if($i % 3 == 0){
echo "Fizz<br />";
}
else if($i % 5 == 0){
echo "Buzz<br />";
}
else {
echo $i."<br />";
}
}
My code is working fine but is there anything wrong with it that I don't see?
Actually they are testing how you will solve such simple task. It should be increadibly optimized, the code shouldbe clean and easy readable.
Your version of code is not good.
The version you've found in the internet is better, but it's not ideal from the point of the optimization.
Try to think how to get the goal with less actions.
Some tips:
do not use functions (such as range) for this task - it will only slow down the script execution time
use operator "for" for this task, do not use any other (while, do-while, foreach), because operator "for" the best fits in this case (you know how many iterations you need).
do not use round function, use modulus operator "%", because any function works slower than any operator
in the result you need to get code, in which the number of operations will be the least as possible (the number of "if" statements, the number of operators like "==" or "%"
Use 15 instead of % 3 && % 5 - less calculations - faster execution time.
My example of code:
for ($i = 1; $i <= 100; $i++) {
if ($i % 15 == 0) {
echo 'FizzBuzz<br>';
} elseif ($i % 3 == 0) {
echo 'Fizz<br>';
} elseif ($i % 5 == 0) {
echo 'Buzz<br>';
} else {
echo $i . '<br>';
}
}
Code style and lack of optimization gives impression of a newbie to the interviewer. My tips are:
Follow PSR-2
Never use else (restructure, use early returns/continues)
Always try to reduce the number of ifs (code complexity)
Use "identical" operators for comparison when dealing with integers and nulls (and any other type)
Do not use <br/> when HTML is never mentioned
Try to keep maintainability:
Extract match calculations in variables/functions, so they can be easily changed
Do not overcomplicate.
Try to optimize mathematically:
Use %15 instead of %3 and %5 check
You can also skip the above at all (check for %15), as you already have calculated that. Boolean operations are much faster.
Try not to calculate something twice.
IMHO, to follow all good practices your code should look like this:
for ($i = 1; $i <= 100; $i++) {
$isFizz = (0 === $i % 3);
$isBuzz = (0 === $i % 5);
if (!$isFizz && !$isBuzz) {
echo $i . PHP_EOL;
continue;
}
if ($isFizz) {
echo 'Fizz';
}
if ($isBuzz) {
echo 'Buzz';
}
echo PHP_EOL;
}
Test
There is yet another tricky solution
for ($i = 1; $i <= 100; $i++) {
switch ($i % 15) {
case 3:
case 6:
case 9:
echo 'Fizz';
break;
case 5:
case 10:
echo 'Buzz';
break;
case 0:
echo 'FizzBuzz';
break;
default:
echo $i;
break;
}
echo PHP_EOL;
}
if you read carefully it says "instead".
this is another short and clean solution of the FizzBuzz problem :
foreach (range(1, 100) as $number) {
if(0 !== $number % 3 && 0 !== $number % 5) {
echo $number.'<br>';
continue;
}
if(0 === $number % 3) {
echo 'Fizz';
}
if(0 === $number % 5) {
echo 'Buzz';
}
echo '<br>';
}
the output is :
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
16
This question already has answers here:
Formatting a number with leading zeros in PHP [duplicate]
(11 answers)
Closed 7 years ago.
I would like to Increment numbers with double digits if the number is less then 10
This is what i tried so far
$i = 1;
echo $i++;
results is 1,2,3,4,5,6 so on
Then i try adding a condition
$i = 1;
if ($i++<10){
echo "0".$i++;
}else{
echo $i++;
}
Work but skipping the numbers 2,4,6,8 so on.
Can anyone tell me the proper way to do this?
If the condition is only there for the leading zero you can do this much easier with this:
<?php
$i = 10;
printf("%02d", $i++);
?>
if you want prepend something to a string use:
echo str_pad($input, 2, "0", STR_PAD_LEFT); //see detailed information http://php.net/manual/en/function.str-pad.php
On the second fragment of code you are incrementing $i twice, that's why you get only even numbers.
Incrementing a number is one thing, rendering it using a specific format is another thing. Don't mix them.
Keep it simple:
// Increment $i
$i ++;
// Format it for display
if ($i < 10) {
$text = '0'.$i; // Prepend values smaller than 10 with a zero
} else {
$text = $i;
}
// Display it
echo($text);
<?php
$i = 1;
for($i=1;$i<15;){
if($i<10){
echo '0'.$i++."<br>";
}else{
echo $i++."<br>";
}
}
?>
I realize this is extremely simple but I feel I'm over-looking something.
What I want to screen to display is
RED This is 0.
or
GREEN This is 1.
And for it to alternate back and forth between the displayed text. My logic if fine for alternating between Red and Green, but the "This is 0" and "This is 1" text is not displaying.
Here is my code so far:
<?php
$array = array(0=>"RED",1=>"GREEN");
$a_count = 0;
$count = 0;
while($count<10)
// DO 9 TIMES
{
echo $array[$a_count] . ' ';
//SUDO FOR IMAGE BEING DISPLAYED
while($array[$a_count] == 0)
{
echo "This is 0.<br>";
}
while($array[$a_count] == 1)
{
echo "This is 1<br>";
}
//<----SWITCH BACK AND FORTH---->
if($a_count == 1)
{
$a_count = 0;
}
else
{
$a_count++;
}
//<----------------------------->
$count++;
}
?>
I realize the easiest way to get what I would like is:
<?php
$array = array(0=>"RED",1=>"GREEN");
$a_count = 0;
$count = 0;
while($count<10)
// DO 9 TIMES
{
echo $array[$a_count] . ' ';
//SUDO FOR IMAGE BEING DISPLAYED
//<----SWITCH BACK AND FORTH---->
if($a_count == 1)
{
echo "This is 1<br>";
$a_count = 0;
}
else
{
echo "This is 0.<br>";
$a_count++;
}
//<----------------------------->
$count++;
}
?>
But this code does not contain the logic I need for the continuation of this project.
I would greatly appreciate an answer as to why my first code is not printing "This is 0."
Thank you!
What you are looking for is a mod count.
Change your loop for:
for($i=0;$i<10;$i++){
echo $array[$i%2].' This is '.($i%2);
}
The modulo operator returns the remainder of a division.
See: What are the practical uses of modulus (%) in programming?
Why not something like this:
$colors = array(0 => 'Red', 1 => 'Green');
$idx = 0;
$count = 0;
while($count < 10) {
echo "The color is {$colors['$idx']}<br />";
$count = 1 - $count; // if $count is 1, it becomes 0. if it's 0, it becomes 1
}
Your while() loops are basically totally useless. You're trying to compare the RED and GREEN strings again 0. If either evaluation happens to be true, you'll end up with an infinite loop.
Ignoring the inefficiency of this script, your while loops are comparing against the array's values, not its keys. But fixing this problem will actually expose another - an infinite loop.
You aren't changing the value of $a_count in your while loops, so there is no way for them to end.
The problem is here:
while($array[$a_count] == 0)
{
echo "This is 0.<br>";
}
while($array[$a_count] == 1)
{
echo "This is 1<br>";
}
Once it enters the first loop, it will just keep echoing "This is 0.<br>", as $a_count is unchanging.
It looks like you could change these whiles to ifs to make your code work the way you want. You also probably want to check that $a_count is 0 or 1, rather than $array[$a_count]
Well, in your first example before the while($count<10), have you initilize your values?
If you do, you must have a display like that :
RED This is 0.0
This is 0.0
This is 0.0
This is 0.0
This is 0.0
...
"This is 0.0" is display in a infinite loop.
while($array[$a_count] == 0)
{
echo "This is 0.$count<br>";
}
while($array[$a_count] == 1)
{
echo "This is 1<br>";
}
You must change the value in a while loop.
Other tips, I think you mush take a look at "foreach" php loop. Can be useful for what you want to do. modulos can also help you.
I think probably the easiest way to do this is to just use a switch statement. I feel really silly for not thinking of it before.
while($count<10)
{
echo $array[$a_count] . ' ';
//PSUEDO FOR IMAGE BEING DISPLAYED
switch($a_count):
{
case 1:
echo "This is RED.<br>";
$a_count = 0;
break;
case 0:
echo "This is GREEN.<br>";
$a_count++;
break;
}
$count++;
}
This question already has answers here:
Compare floats in php
(17 answers)
Closed 9 years ago.
hello I have a problem wtich two variables in php. i have this code:
var_dump($total);echo '<br/>';
var_dump($reserva->getAdelanto());
if ($total == $reserva->getAdelanto()){
$total = 0;
echo "hello";
}
else
$total = $total - $reserva->getAdelanto();
print :
float(3940.2)
float(3940.2)
but does not enter the if when the two variables are equal. anyone knows why is that? greetings and thanks.
May be try with abs like
if ((abs($a)-abs($b)) <= 0.00001) {
echo "same";
}
Or
if (abs($a - $b) <= 0.00001) {
echo "same";
}
Or you also try like
var_dump( bccomp($a, $b) == 0 )
returns true if they are same