I am trying to get multiple number of 2 and 3 pls help. Thanks
for($i = 0; $i <30; $i++)
if($i % 2)
echo 'number is '. $i . ' is multiple of 2 <br/>';
elseif($i %3)
echo 'number is '. $i . 'is multiple of 3 <br/>';
else
echo 'number is '. $i . 'is multiple of some other number <br/>';
Try this:
if($i % 2 === 0)
...
elseif($i %3 === 0)
...
Basically if the modulo is 0 then that means the number is evenly divisible.
However, another problem with your logic is that a number may be divisible by both 2 and 3. You can fix this by extracting these out into separate if statements:
if($i %2 === 0) {
...
}
if($i %3 === 0) {
...
}
But that sort of breaks your last else since you cannot just fall though to it anymore. You could solve that by setting a variable to false at the top of your loop. Then if any of your if statements is triggered, set the variable to true. Finally, print the "not divisible" message at the end of each iteration if the variable is still false.
You want a NOT if(i%2) because it is a multiple if the remainder is zero.
Additionally if you're trying to find multiples of 30 you only need to loop up to 15. Or number/2.
for($i = 0; $i < 30; $i++)
{
if($i % 2 == 0)
echo 'number is '. $i . ' is multiple of 2 <br/>';
elseif($i % 3 == 0)
echo 'number is '. $i . 'is multiple of 3 <br/>';
else
echo 'number is '. $i . 'is multiple of some other number <br/>';
}
I would add one more condition before your if conditions
if($i%2 === 0 && $i%3 === 0) {
echo 'multiple of 2 and 3\n';
}
It may also be correct to use:
if ($i%6 === 0) {
....
}
for the above if condition.
Even better if you use a switch case block.
Related
I am trying to work out how to use the modulus function in PHP with this simple example using a WordPress loop I am wanting to echo out a message every 1, 2 and 3rd iterations of the loop...
if ( $the_query->have_posts() ) {
$counter = 0;
while ( $the_query->have_posts() ) {
$counter++;
$the_query->the_post();
if ($counter % 1 == 0) {
$output .= '1 - ' . $counter . '<br />------------<br />';
} elseif ($counter % 2 == 0) {
$output .= '2 - ' . $counter . '<br />------------<br />';
} elseif ($counter % 3 == 0) {
$output .= '3 - ' . $counter . '<br />------------<br />';
}
}
}
I am seeng this when I run it thoughh..
1 – 1
————
1 – 2
————
1 – 3
————
Can anyone tell me why I am seeing these results? I was expecting to see the echo 1 2 and 3 be output for the 1st second and third row.
Every time you divide an integer by one there is no remainder!
Therefore the line
if ($counter % 1 == 0)
is always true!
Because it always satisfy first condition:
// no matter what value is $counter , it always satisfy that the given value is always divisible by 1 and hence remainder will be 0
if ($counter % 1 == 0) {
$output .= '1 - ' . $counter . '<br />------------<br />';
``
That's why it don't go for other conditions
Hi guys I tried to echo this using php
even odd odd even odd odd
and so on .
My code :
For( $i = 0 ; $i <=11; $i++ ){
If( $i % 2 == 0 ) {
echo " even " ;
}
If( $i % 2 != 0 ) {
echo " odd " ;
$i = $i+1 ;
}
}
And sure the result is :
even odd odd odd ood
and so on .
I wanted to repeat ( even ) one time and ( odd ) twice and so on ..
Can someone help me in that ? Thanks
You can use% operator.
Where any counter that is exactly divisible by 3 is even, other case is odd.
Answer:
for ($i=0 ; $i<=11 ; ++$i) {
if ($i%3==0) {
echo "Even";
}
else {
echo "Odd";
}
}
Hand Run:
$i - $i%3 - Output
--------------------
0 - 0 - Even
1 - 1 - Odd
2 - 2 - Odd
3 - 0 - Even
4 - 1 - Odd
5 - 2 - Odd
6 - 0 - Even
7 - 1 - Odd
8 - 2 - Odd
9 - 0 - Even
10 - 1 - Odd
11 - 2 - Odd
EDIT: Using ternary operator, you can even reduce the lines of code.
Reduced Code:
for ($i=0 ; $i<=11 ; ++$i) {
echo ($i%3==0) ? 'Even' : 'Odd';
}
In this case, you could simply use modulo 3 instead of 2 with a if-else statement
for ($i = 0; $i < 11; $i++) {
if ($i % 3 == 0) {
echo 'even ';
} else {
echo 'odd ';
}
}
I'm not sure if you want the desired behaviour of using % 3 as suggested by the others (even though it gets you the result you want) but i'm not sure you'd get the same 'count'. So I'm just going to simply say, why don't you just write 'odd' in your echo statement twice?
for( $i = 0 ; $i <=11; $i++ ){
if( $i % 2 == 0 ) {
echo " even " ;
}else {
echo " odd odd ";
}
}
If you could help us understand why you want to print odd out twice on the odd numbers that would help? Or whether it doesn't actually matter if i is even or odd itself but just the output you're after (as suggested by using % 3).
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
I am attempting to show data in rows of three like this (notice the number of items will not always be even):
abcd defg hijk
lmno pqrs tuvw
xyz1 2345 6789
1011 1213
I am struggling to get the logic right to do this (this is in a foreach() loop).
I know I have to have some if($i %3 == 0) logic in there.. But I'm a bit stuck.
Can anyone help me out?
$a = array('abcd','defg','hijk','lmno');
for ($i = 0; $i < count($a); $i++) {
if ($i && $i % 3 == 0)
echo '<br />';
echo $a[$i].' ';
}
It's better to use a for loop as:
// run $i for each index in the array.
for($i=0 ; $i<count($arr) ; $i++) {
// if $i is non-zero and is divisible by 3 print a line break.
if ($i && $i % 3 == 0) {
echo "<br />";
}
// print the element at index $i.
echo $arr[$i].' ';
}
Code in action
Pseudo-code since I don't know PHP (and you asked for the logic which tends to be the same across all procedural languages):
perline = 3
i = 0
foreach item in list:
if i > 0 and (i % perline) == 0:
print newline
if (i % perline) != 0:
print space
print item
i = i + 1
This will both output a line separator before elements 3, 6, 9 and so on (first element being 0) and place whatever desired spacing you want before the second and third elements on each line. You can just use a different value for perline to change the number output on each line.
I wanted to echo an image every after 3 post via XML here is my code :
<?php
// URL of the XML feed.
$feed = 'test.xml';
// How many items do we want to display?
//$display = 3;
// Check our XML file exists
if(!file_exists($feed)) {
die('The XML file could not be found!');
}
// First, open the XML file.
$xml = simplexml_load_file($feed);
// Set the counter for counting how many items we've displayed.
$counter = 0;
// Start the loop to display each item.
foreach($xml->post as $post) {
echo '
<div style="float:left; width: 180px; margin-top:20px; margin-bottom:10px;">
image file</a> <div class="design-sample-txt">'. $post->author.'</div></div>
';
// Increase the counter by one.
$counter++;
// Check to display all the items we want to.
if($counter >= 3) {
echo 'image file';
}
//if($counter == $display) {
// Yes. End the loop.
// break;
//}
// No. Continue.
}
?>
here is a sample first 3 are correct but now it doesn't loop idgc.ca/web-design-samples-testing.php
The easiest way is to use the modulus division operator.
if ($counter % 3 == 0) {
echo 'image file';
}
How this works:
Modulus division returns the remainder. The remainder is always equal to 0 when you are at an even multiple.
There is one catch: 0 % 3 is equal to 0. This could result in unexpected results if your counter starts at 0.
Going off of #Powerlord's answer,
"There is one catch: 0 % 3 is equal to 0. This could result in
unexpected results if your counter starts at 0."
You can still start your counter at 0 (arrays, querys), but offset it
if (($counter + 1) % 3 == 0) {
echo 'image file';
}
Use the modulo arithmetic operation found here in the PHP manual.
e.g.
$x = 3;
for($i=0; $i<10; $i++)
{
if($i % $x == 0)
{
// display image
}
}
For a more detailed understanding of modulus calculations, click here.
every 3 posts?
if($counter % 3 == 0){
echo IMAGE;
}
You can also do it without modulus. Just reset your counter when it matches.
if($counter == 2) { // matches every 3 iterations
echo 'image-file';
$counter = 0;
}
How about: if(($counter % $display) == 0)
I am using this a status update to show a "+" character every 1000 iterations, and it seems to be working good.
if ($ucounter % 1000 == 0) { echo '+'; }
It will not work for first position so better solution is :
if ($counter != 0 && $counter % 3 == 0) {
echo 'image file';
}
Check it by yourself. I have tested it for adding class for every 4th element.