PHP Counting Negative Numbers and Bold Only Even Numbers - php

On a form, I used PHP to display every number from 1 to the entered number. For example, if I enter 10 on the form, it displays 1 2 3 4 5 6 7 8 9 10. Now, I want it to be able to handle negative numbers by counting up to 0 (-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0) and make every even number in the results bold, e.g., 2 4 6 8 10, etc.). I've searched exhaustively for the answers without any luck. How would any of you suggest doing this? My code for the first part is displayed below. Thank you in advance.
<?php
$num = $_POST['num'];
$limit = $_POST['num'];
echo "<pre>";
do {
echo ($counter).'<br>';
$counter++;
} while ($counter <= $limit);
echo "<pre>";
?>

You can do this
<?php
$num = $_POST['num'];
$limit = $_POST['num'];
echo "<pre>";
do {
if( $counter % 2 == 0 )
{
echo "<strong>" . $counter . "</strong><br />";
}
else
{
echo ($counter).'<br>';
}
$counter++;
} while ($counter <= $limit);
echo "<pre>";
?>
Solution 1
Ok, some more information about the %. This is a modulo. It gives you back the remaining number if you divide it by the mod number. For example
0 % 2 = 0
1 % 2 = 1
2 % 2 = 0
3 % 2 = 1 this because 3 / 2 = 1 and a bit,
you can't divide the last 1 completely by 2. So remain 1
4 % 2 = 0
Solution 2
Like crush said, you can use $counter & 1. What does this do?
If you look at a number bitwise. You want to AND it wit 1.
Bitwise number 2 = 0010 AND it with 0001 and your return will be 0000 (zero).
Bitwise number 3 = 0011 AND it with 0001 and your result will be 0001 (one).
If you ceep that going and only check the last bit, you can see if it is a even number. More about bitwise operations.

Related

convert switch statement to one if only in PHP

I am trying to print numbers from 1 to 50. for multiple of 3 it should print "multiple of 3". for multiple of 5 it should print "multiple of 5". for multiple of 3 and 5 it should print "multiple of 3 and 5 both" for other numbers it should print that number.
I tried this below code using switch, it is working. but i can't use switch, ternary operator or else statement.
Below is my code -
function findMultiples($n)
{
$three = 3; // To keep track of multiples of 3
$five = 5; // To keep track of multiples of 5
for ($i = 1; $i <= $n; $i++)
{
switch ($i) {
case $i%$three==0 and $i%$five==0:
echo "multiple of 3 and 5 both";
break;
case $i%$three==0:
echo "multiple of 3";
break;
case $i%$five==0:
echo "multiple of 5";
break;
default:
echo $i;
}
echo "<br/>";
}
}
// Driver Code
findMultiples(50); //I am getting expected result.
how can i get this result by using below if condition on place of switch
$printNumbers = "";
if (($i%$three==0 and $i%$five==0) or ($i%$three==0) or ($i%$five==0))
{
$printNumbers = $i;
}
echo $printNumbers;
A bit weird question, but if you need only ONE IF then you can use both comparison and assignment into in order to achieve it:
<?php
function findMultiples($n) {
$three = 3; // To keep track of multiples of 3
$five = 5; // To keep track of multiples of 5
for ($i = 1; $i <= $n; $i++) {
if (($i % $three == 0 and $i % $five == 0 and $text = 'both 3 and 5') or ($i % $three == 0 and $text = '3') or ($i % $five == 0 and $text = '5') or ($text = 'none')) {
echo $i.' is divided by '.$text;
}
echo '<br>';
}
}
findMultiples(50);
Output:
1 is divided by none
2 is divided by none
3 is divided by 3
4 is divided by none
5 is divided by 5
6 is divided by 3
7 is divided by none
8 is divided by none
9 is divided by 3
10 is divided by 5
11 is divided by none
12 is divided by 3
13 is divided by none
14 is divided by none
15 is divided by both 3 and 5
16 is divided by none
17 is divided by none
18 is divided by 3
19 is divided by none
20 is divided by 5
21 is divided by 3
22 is divided by none
23 is divided by none
24 is divided by 3
25 is divided by 5
26 is divided by none
27 is divided by 3
28 is divided by none
29 is divided by none
30 is divided by both 3 and 5
31 is divided by none
32 is divided by none
33 is divided by 3
34 is divided by none
35 is divided by 5
36 is divided by 3
37 is divided by none
38 is divided by none
39 is divided by 3
40 is divided by 5
41 is divided by none
42 is divided by 3
43 is divided by none
44 is divided by none
45 is divided by both 3 and 5
46 is divided by none
47 is divided by none
48 is divided by 3
49 is divided by none
50 is divided by 5
Feel free to change the printed text if needed.

What makes this work?

I am trying to use this chunk of code as template, but Im not fully understanding of how one line works. I'll first provide the full chunk, then I'll single out the line I don't understand.
/** settings **/
$images_dir = 'preload-images/';
$thumbs_dir = 'preload-images-thumbs/';
$thumbs_width = 200;
$images_per_row = 3;
/** generate photo gallery **/
$image_files = get_files($images_dir);
if(count($image_files)) {
$index = 0;
foreach($image_files as $index=>$file) {
$index++;
$thumbnail_image = $thumbs_dir.$file;
if(!file_exists($thumbnail_image)) {
$extension = get_file_extension($thumbnail_image);
if($extension) {
make_thumb($images_dir.$file,$thumbnail_image,$thumbs_width);
}
}
echo '<img src="',$thumbnail_image,'" />';
if($index % $images_per_row == 0) { echo '<div class="clear"></div>'; }
}
echo '<div class="clear"></div>';
}
else {
echo '<p>There are no images in this gallery.</p>';
}
I understand how everything with the exception of this line works.
if($index % $images_per_row == 0) { echo '<div class="clear"></div>'; }
I know it is getting its value from this line:
$images_per_row = 3;
But what actually makes this work? Im still pretty new to php, and I would like a better understanding of the code Im about to use before I use it.
Any answers at all would be appreciative!
$index % $images_per_row == 0
The % means "mod", example 4 mod 2 = 0.
A % B = the remainder when we divide A by B.
In your script, the condition is met (valued to 'true') when the remainder of $index divided by $images_per_row equals 0, meaning the divisibility of $index by $images_per_row.
Hope it helps!
% is the modulo operator. It divides the two numbers and then returns the remainder after the division.
It is quite easy to understand if you remember your fractions and how to reduce them to their lowest terms.
So, if we make 5 % 2 into a fraction and reduce it:
5 1 (this is the remainder)
--- → 2 ---
2 2
So, 5 % 2 = 1.
If we take 8 % 3 we can do the same thing:
8 2 (this is the remainder)
--- → 2 ---
3 3
So, 8 % 3 = 2.
If there is no remainder, such as in 9 % 3 then you will get 0 back. See:
9 0 (this is the remainder)
--- → 3 ---
3 3
You can write some PHP to see what the values are when doing the modulo operations:
$perRow = 3;
for ($i = 0; $i < 10; $i++) {
echo "$i % $perRow = ", $i % $perRow, ' | ', "$i / $perRow = ", ($i / $perRow), "\n";
}
Output:
0 % 3 = 0 | 0 / 3 = 0
1 % 3 = 1 | 1 / 3 = 0.33333333333333
2 % 3 = 2 | 2 / 3 = 0.66666666666667
3 % 3 = 0 | 3 / 3 = 1
4 % 3 = 1 | 4 / 3 = 1.3333333333333
5 % 3 = 2 | 5 / 3 = 1.6666666666667
6 % 3 = 0 | 6 / 3 = 2
7 % 3 = 1 | 7 / 3 = 2.3333333333333
8 % 3 = 2 | 8 / 3 = 2.6666666666667
9 % 3 = 0 | 9 / 3 = 3

Reduce a number to single digit by adding its digits recursively

How to reduce a number to single digit by adding its individual digits recursively :
Example 1 : $n = 99999 >> 45 >> 9
Example 2 : $n = 444444 >> 24 >> 6
Example 3 : $n = 8888888888888885 >> 125 >> 8;
then get equal to at last we want to get single digit.
You can use array_sum and str_split into a while loop until the final value of $n has the length equal to 1.
$n = 4444;
while (strlen($n) > 1) {
$n = array_sum(str_split($n));
}
var_dump($n);
Without array_sum and str_split you can use something like:
$n = '4444';
while (strlen($n) > 1) {
$s = 0;
for ($i = 0; $i < strlen($n); $i++) {
$s += $n[$i];
}
$n = (string) $s;
}
var_dump($n);
You can calculate this in a much more simple and elegant way, let me try to explain. For example if you have the number 53, you can divide it by 9 and it’s remainder will be it’s reduced number. Don’t ask me how I figured this out, I was just tinkering with numbers. So what you can do is use modulus, (53 % 9 = 8!) (517 % 9 = 4!). Perfect right? Almost, if the number is a multiple of 9 like 45 for example if you “modulus” it by 9 you will receive it’s remaineder which is 0 and we would expect 9 because 45 reduced to a single digit is 9. So you can just make a quick and easy else if statement checking for an output of 0, and if it’s 0 just return 9. Done! Whatever number you out in from 1 to infinty it will reduce it perfectly. Hope this helps :)

how can this algorithm be optimized

I am trying to find the smallest positive number that is evenly divisible by all of the numbers from 1 to 20 and here is the code:
$num = 2520;
$x = 1;
while($x < 21){
if($num % $x == 0){
$x++;
}else{
$num += 20;
$x = 1;
}
}
echo $num;
it gives a proper output in less than 1 minute. Is this execution time bad in the professional world? any way to optimize this?
P.S. I started from 2520 because it is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder.
Suggestion: find the primes of all integers in [1,20].
Eg, we have the primes {2,3,5,7,11,13,17,19}. So, if the solution is divisible
by all integers in [1,20], then surely it is divisible by each element in this
list of primes. So, at a minimum, our solution is >= 2*3*5*7*11*13*17*19, right?
Now the problem is how clever we can be about constructing candidate solutions
larger than that number. Well, let's first see how much of the solution is done...
Is 2*3*5*7*11*13*17*19 divisible by 4? No. So, let's multiple by 2 to get
2*2*3*5*7*11*13*17*19, which surely is divisible by 2*2...
Is 2*2*3*5*7*11*13*17*19 divisible by 6? Yes.
Is 2*2*3*5*7*11*13*17*19 divisible by 8? ....
You get the picture. While I am not sure, I believe this approach will
result in the right answer -- ie, the smallest integer divisible by each
integer in [1,20].
use modified Sieve of Eratosthenes for massive speed up
http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes
but do not use array instead iterate just indexes
something like
1.int ix[20]={1,2,3,4,...20};
2.now write a loop
where you will increment all ix[i]+=i+1; where i=<0;18>
while ix[i]>=ix[19]
if at the end all ix[i] are the same then its contens is the result so stop/return whatever
3.if not then increment also ix[19]+=20;
and continue with the loop on bullet 2
[notes]
can be easily changed for searing for divisible by any numbers not just divisible by 1..20
This sounds like Project Euler's Problem 5.
What we are finding here is the least common multiple of numbers 1 to 20. You can find this with help form the greatest common divisor:
function gcd($a, $b) {
if ($a == 0) return $b;
return gcd($b % $a, $a);
}
function lcm($a, $b) {
return $a * $b / gcd($a, $b);
}
function smallestDiv($n) {
$div = 1;
for ($i = 1; $i <= $n; $i++) {
$div = lcm($div, $i);
}
return $div;
}
echo smallestDiv(20);
Pardon my PHP. It's been a while since I have written any.
Note that we can also find the answer via prime factorization of each of the numbers and looking for the largest exponents as described here and in Kode Charlie's answer:
2 = 2
3 = 3
4 = 2²
5 = 5
6 = 2 × 3
7 = 7
8 = 2³
9 = 3²
10 = 2 × 5
11 = 11
12 = 2² × 3
13 = 13
14 = 2 × 7
15 = 3 × 5
16 = 2⁴
17 = 17
18 = 2 × 3²
19 = 19
20 = 2² × 5
lcm(1,2,…20) = 2⁴ × 3² × 5 × 7 × 11 × 13 × 17 × 19 = 232,792,560

Alternating Designs For Loop Results

I am looking to create alternating designs for the content of each post returned in my loop. In short I want the first post to display left align, next right align, and so on. I have not been able to find a way to do this. Any ideas?
Try something like this:
$count = 0;
foreach ($posts as $post) {
echo "<div class=\"" . (++$count % 2 ? 'left' : 'right') . "\">"
. $post['postText'] // or whatever the crazy wordpress thing is
. "</div>"
;
}
You could loop through the results and then check if an incremented counter is even or odd and display left or right depending on that.
Have a look at the modulo operator '%'
0 % 2 = 0
1 % 2 = 1
2 % 2 = 0
3 % 2 = 1
...
100 % 2 = 0
101 % 2 = 1
You can have a repeating pattern of as many as you like:
0 % 4 = 0
1 % 4 = 1
2 % 4 = 2
3 % 4 = 3
4 % 4 = 0
5 % 4 = 1
....
C.

Categories