Looping issue PHP - php

Here is the code:
$TopFive = array_slice($counts,0,5);
{
foreach($TopFive as $key => $tops)
{
for($i=0; $i<$tops; $i++)
{
echo "*";
}
$b=0;
for($a=0; $a<5; $a++)
{
$b++;
}
echo "{$b}";
echo "#:{$key} - {$tops} <br/>";
}
}
currently, the output looks this:
*********5#:THE - 9
*****5#:OF - 5
*****5#:TO - 5
***5#:AND - 3
***5#:THEM - 3
but what I really want to have is this:
********* #1: THE - 9
***** #2: OF - 5
***** #3: TO - 5
*** #4: AND - 3
*** #5: THEM - 3
I can't seem to figure out how to arrange the looping. Any ideas? I am very sorry this simple question, I ran out of ideas. I just want the numbers to be from 1-5.
I just want some advice as to how to arrange the looping for the $b so that the counting will be from 1-5, not just 5

If:
$TopFive = array('THE' => 9, 'OF' => 5, 'TO' => 5, 'AND' => 3, 'THEM' => 3);
then:
$number = 1;
foreach ($TopFive as $word => $count)
{
echo str_repeat('*', $count); // Outputs '*' characters
echo " #{$number}: {$word} - {$count}\n";
$number++; // increment your number
}
Here's an example.

Your this line has problem
for($a=0; $a<5; $a++)
$b always increments to 5
To solve this, just initialize $x (or anything) outside foreach loop with 1. Do away with $b and simply echo $x; $x++; at appropriate place.

You can change your code to:
$b=1;
foreach($TopFive as $key => $tops)
{
for($i=0; $i<$tops; $i++)
{
echo "*";
}
echo "#$b:{$key} - {$tops} <br/>";
$b++;
}
but all the inner loops are redundant.

In your code, please change this part:
echo "{$b}";
echo "#:{$key} - {$tops} <br/>";
To:
// echo "{$b}";
echo "#$i:{$key} - {$tops} <br/>";
And use str_repeat('*', $count) instead of a for loop! :)

Related

How to print odd/even series without if-statement

I'm writing program to list odd/even series from n elements (1,2,...n) using if-statement.
For example,
n = 1
Odd Series
1
3
5
7
9
Even Series
0
2
4
6
8
If any possible to print odd/even series without if-statement.
You can just use range with a step of 2, starting with either 0 or 1 as required:
echo "Odd Series\n";
foreach (range(1, 9, 2) as $v) echo "$v ";
echo "Even Series\n";
foreach (range(0, 9, 2) as $v) echo "$v ";
Output:
Odd Series
1 3 5 7 9
Even Series
0 2 4 6 8
Demo on 3v4l.org
Yes. This is possible. We can list odd or even series without if-condition.
We use Increment operator insteed of if-condition.
Sample code is,
<?php
echo "Odd Series";
echo "<pre>";
for ($i=0; $i < 10; $i++) {
echo ++$i;
}
echo "Even Series";
echo "<pre>";
for ($i=0; $i < 10; $i++) {
echo $i++;
}
?>
Sample output is here,
Odd Series
1
3
5
7
9
Even Series
0
2
4
6
8
We could try using a ternary expression in lieu of an if statement:
// even series
for ($i = 0; $i < 10; $i++) {
echo $i % 2 == 0 ? $i : "\n";
}
Another possibility is to just iterate the for loop by steps of 2:
for ($i = 0; $i < 10; $i=$i+2) {
echo $i . "\n";
}
Using arrays, you can create the range with range(), and use array_filter() to pluck the odd or even values using bit-operators.
$n = 8;
$series = range(1, $n);
$odd = array_filter($series, function($value) { return $value & 1; });
$even = array_filter($series, function($value) { return !($value & 1); });
var_dump($odd, $even);
Then its just a matter of looping the arrays $odd and $even.
echo "Odd values: \n";
foreach ($odd as $v) {
echo $v."\n";
}
echo "Even values: \n";
foreach ($even as $v) {
echo $v."\n";
}
Live demo at https://3v4l.org/J9Dio

Nested Loop PHP

i have code :
<?php
$number =9;
$number2 = $number / 2;
for ($b=0; $b<=$number2; $b++){
for ($i=$number; $i>=1; $i--){
echo $i;
}
echo "<br/>";
for ($a=1; $a<=$number; $a++)
{
echo $a;
}
echo "<br/>";
}
?>
I want the result like this .
987654321
123456789
987654321
123456789
987654321
123456789
987654321
123456789
987654321
why if i put odd number like 9 , why always the result 10 loop ?
You have two loops in a loop, therefore you'll always get an even number of lines.
You don't actually need that structure, see:
$number=9;
$k=0;
$sum=1;
for($i=1; $i<=$number; $i++) {
for($j=1; $j<=$number; $j++) {
$k+=$sum;
echo $k;
}
echo '<br>';
//Sum once again so in the next iteration $k is 0 or 10
$k+=$sum;
//Invert the sign of $sum so in the next iteration it substracts, and then adds, and so on
$sum*=-1;
}
Also note that going from 0 to $number inclusive (lower or equal comparation) you'll get one iteration more (from 0 to 9 there are 10 whole numbers).
Solve with this code , thx Gabriel.
$number=9;
$k=0;
$sum=1;
for($i=1; $i<=$number; $i++) {
for($j=1; $j<=$number; $j++) {
$k+=$sum;
echo $k;
}
echo '<br>';
//Sum once again so in the next iteration $k is 0 or 10
$k+=$sum;
//Invert the sign of $sum so in the next iteration it substracts, and then adds, and so on
$sum*=-1;
}

Create line breaks in output based on array index

I want to display output like this:
1 2 3 4
5 6 7 8
9 1 2
I've tried this code:
$num = ['1','2','3','4','....'];
$size = sizeof($num) / 4;
foreach ($num as $key => $value) {
echo $value;
if($key >= round($size){
echo "<br>"
}
}
But the output is like this:
1 2 3 4
5
6
7
8
...
Can anyone suggest how to write the loop?
$num= ['1','2','3','4','5','6','7','8','9'];
$size = sizeof($num) / 4;
foreach ($num as $key => $value){
echo $value;
if(($key+1) % 4 == 0){
echo "<br>";
}
}
You can use modulus instead of round. Cool I didn't know about sizeOf! Good to know. Mark this as the right answer pwease if this works!
Another way to do this if you didn't want to write out all the numbers that are in the Num Array is to just push them into an array with a while loop.
$num= [];
$i = 1;
//Set the Num Variable to have as many numbers as you want without having to manually enter them in
while ($i < 100) {
array_push($num, $i);
$i++;
}
//Run the actual code that adds breaks ever 4 lines
$size = sizeof($num) / 4;
foreach ($num as $key => $value){
echo $value;
if(($key+1) % 4 == 0){
echo "<br>";
}
}
Sorry if this answer looks the same as the first answer but I will explain it clearer
To achieve what you want
Step 1: Create a for loop
The loop will start from 1 to it's total size of the array
for ($x = 1; $x <= sizeof($num); $x++){
}
Then inside your loop
you can use ternary for simplicity
This line of code
# if $x variable is equal to limit number which you wanted to break
# $num[$x-1] -> subtract to by 1 because we know array always start at index 0
if ($x % 4 == 0) {
$num[$x-1]."<br>"; #put a break after it
} else {
echo $num[$x-1];
}
is same as this
echo ($x % 4 == 0) ? $num[$x-1]."<br>" : $num[$x-1];
So try this
<?php
$num= ['1','2','3','4','5','6','7','8','9','10','11','12','13','14','15','16'];
$size = sizeof($num) / 4;
for ($x = 1; $x <= sizeof($num); $x++){
echo ($x % 4 == 0) ? $num[$x-1]."<br>" : $num[$x-1];
}
DEMO
You can try this:
$numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 8, 19, 20];
$len = 1;
foreach ($numbers as $number) {
echo $number . ' ';
$len++;
if ($len > 4) {
echo '<br>';
$len = 1;
}
}

I am facing a small bump printing number pyramids , still a newbie to php and programming

What i want to print is
1
3 5
7 9 11
With my current code , that is ...
<?php
function Odd($limit='20'){
$c = 1;
while($c <= $limit){
if ($c % 2!=0){
echo $c ;
echo "<br/>";
}
$c++ ;
}
}
Print Odd();
?>
i am getting
1
3
5
7
9
11
Can someone please guide me the right way ?
Aaah ... ok.^^ Now i got it.
Its pretty easy: You need another variable which counts up and one which limits the breakposition. Looks like this:
<?php
function Odd($limit='40'){
$c = 1;
$count = 0;
$break = 1;
while($c <= $limit){
if ($c % 2!=0){
echo $c . " ";
$count++;
if($count === $break) {
echo "<br/>";
$break++;
$count = 0;
}
}
$c++ ;
}
}
Print Odd();
?>
Output till 40:
1
3 5
7 9 11
13 15 17 19
21 23 25 27 29
31 33 35 37 39
Edit: Code for your new request:
<?php
function Odd($limit='40'){
$c = 1;
$count = 0;
$break = 1;
while($c <= $limit){
echo $c . " ";
$count++;
if($count === $break) {
echo "<br/>";
$break++;
$count = 0;
}
$c++ ;
}
}
Print Odd();
?>
So if I understand correctly you want to output something like that:
1
3 5
7 9 11
13 15 17 19
Here is my solution:
function Odd($limit='20'){
$c = 1;$some_array = array();
while($c <= $limit){
if ($c % 2!=0){
$some_array[]=$c;
}
$c++ ;
}
return $some_array;
}
$array = Odd();
$nr =0;
$j=1;
foreach ($array as $key => $value) {
echo $value.' ';$nr++;
if($nr==$j){
echo '<br />';
$nr=0;
$j++;
}
}
Hope this helps!
From your question it Seems you are really new to programming so before writing any program first of all observe the question properly:
For example for the question above it is clear that is an triangle of odd numbers.
now the number of odd numbers on each row is equal to the row
i.e 1st row contains 1 number ,2nd contains 2 and it continues...
Now what we do is take an variable to count the no of rows say $row and the other will be $limit .
<?php
function odd($limit){
$row=1;
$current_number=1;
while($current_number<=$limit){
for($i=1;$i<=$row;$i++){
echo $current_number." ";
$current_number=$current_number+2;//incrementing numbers by 2 if you want to increment by 1 i.e print all numbers replace 2 by 1
}
$row++;
echo "<br/>";//for new line
}
}
To run above function you need to call it and pass the value of $limit.To do it just type anywhere outside of this function.
odd(20);
Watch this running here:

php count even numbers in an array

So I am trying to learn php, and the code for finding even numbers doesn't output anything, but I can't seem to find the error, can anybody find where I have made my stupid mistake? Here is the code:
<?php
/*this sets the array up with the data*/
$myarray = array(1,2,3,4,5,6,7,8,9,10);
/* this is the count to get the total number from my array */
$total = count($myarray);
?>
<h1>Display all even numbers</h1>
<ul>
<?php for ($i=1; $i < total; $i += 2): ?>
<li>The array element value is <?php echo $myarray[$i]; ?>. </li>
<?php endfor; ?>
</ul>
Thanks and if nobody wants to post an answer I understand new questions are frustrating.
thanks
Your code isn't finding even numbers. You're identifying their positions in the array, and printing values only for those indexes. Look at this php snippet.
<?php
$myarray = array(1,2,3,4,5,6,7,8,9,10);
// Array indexes start at 0, not 1.
for ($i = 0; $i < count($myarray); $i++) {
echo "Index ", $i, ", value ", $myarray[$i], ": ";
// A value is even if there's no remainder when you divide it by 2.
if ($myarray[$i] % 2 == 0) {
echo "even\n";
}
else {
echo "odd\n";
}
}
?>
Put that in a file, and run it through php. You should see this.
Index 0, value 1: odd
Index 1, value 2: even
Index 2, value 3: odd
Index 3, value 4: even
Index 4, value 5: odd
Index 5, value 6: even
Index 6, value 7: odd
Index 7, value 8: even
Index 8, value 9: odd
Index 9, value 10: even
This shorter version will print only the even values.
<?php
$myarray = array(1,2,3,4,5,6,7,8,9,10);
for ($i=0; $i < count($myarray); $i++) {
if ($myarray[$i] % 2 == 0) {
echo "Index ", $i, ", value ", $myarray[$i], "\n";
}
}
?>
Index 1, value 2
Index 3, value 4
Index 5, value 6
Index 7, value 8
Index 9, value 10
You're missing the $ variable creator in your for loop for total:
<?php for ($i=1; $i < $total; $i += 2): ?>
This code fits your problem.
<?php
$myarray = array(1,2,3,4,5,6,7,8,9,10);
$total = count($myarray);
echo "<h1>Display all even numbers</h1>";
echo "<ul>";
foreach($myarray as $rw)
{
if(($rw%2) == 0 ){
echo "<li>".$rw."</li>";
}
}
echo "</ul>";
?>
The modulus operator % is the best way to get the odd or even numbers in an array.
printing a even number in php. there $ais 20 when you run this code the out put is 2, 4, 6, 8, 10, 12, 14, 16, 18, 20,
$a = 20
for ($i=0; $i < $a; $i += 2)
{
echo "</n><br>".$i;
}
Out put like this
2
4
6
8
10
12
14
16
18
20

Categories