is it possible in php loop without nested loop [closed] - php

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 want to print like this using loop without nested loop:
1
2 3
4 5 6 7
8 9 10 11 12 13 14 15
first line start from 1 and print only one integer
second line start from 2 and print two integer
third line start from 4 and print four integer
fourth line start from 8 and print eight integer
(same condition in other line if exist)

A pair of counters should do the trick;
$threshold = 1;
$x = 1;
for($i = 1; $i <= 15; $i++) {
echo $i . ' ';
if($x == $threshold) {
echo "<br>\n";
$threshold = $threshold * 2;
$x = 0;
}
$x++;
}
Will keep on working till infinity, or your script runs out of memory. Whatever comes first :)

You can achieve with single while and some array functions. Try this.
<?php
$start=1;
while($start<=10){
$array = range($start,($start+$start-1));
echo implode(' ',$array)."<br>";
$start=$start*2;
}
?>

something like this?
$i=1;
$t=1;
while($i<1000)
{
if($i==$t)
{
if($t!=1) echo "<br />";
$t=$t*2;
}
echo $i." ";
$i++;
}

same thing but with log($i,2).
<?php
$i=1;
while($i<20)
{
echo $i;
$i++;
if(filter_var(log($i,2), FILTER_VALIDATE_INT))
echo PHP_EOL;
else
echo "\t";
}

You can even do it without any for and some recursion ;-)
<?php
$elements = range(1,15);
display($elements);
function display(array $parts, $step = 1) {
if(! count($parts)) {
return;
}
$elements = array_splice($parts, 0, $step);
echo implode("\t", $elements)."\n";
display($parts, $step * 2);
}
See the working code on https://eval.in/755277

Related

Nested Loops headache PHP [closed]

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 2 years ago.
Improve this question
How would you go about answering a question like this? I know I would have to use a loop, but my current answer won't allow me to go over an input of about 5 which is incredibly inefficient. I'm finding nested loops a little daunting.
Given the triangle of consecutive odd numbers:
1
3 5
7 9 11
...
Calculate the row sums of this triangle from the row index (starting at index 1)
rowSumOddNumbers(1); // 1
rowSumOddNumbers(2); // 3 + 5 = 8
Disclaimer - this is not a test questions. Just one of the practice ones I'm struggling to get my head around.
Since posting this I have found a working answer (three hours later...)
Working code:
function rowSumOddNum($n) {
$start = ($n *($n - 1)) + 1;
$sum = 0;
$step = $start +($n*2);
for($a=$start;$a<$step;$a++){
if($a % 2 !== 0){
$sum = $sum + $a;
}
} echo $sum;
}
This was the original code I was working with that kept crashing out saying it didn't have enough memory. Very inefficient I believe.
function rowSumOddNumbers($n) {
$len = $n + ($n*1);
$array = [];
for ($i = 1; $i <= $len; $i+2) {
if ($i % 2 == 1) {
$array[] = $i;
}
}
$count = 0;
$answer = 0;
for ($row = 1; $row < $n; $row++) {
$count = $count + $row;
}
$length = $count + $n;
for ($a = $count; $a <$length; $a++) {
$answer = $answer + $array[$a];
}
echo $answer;
}
I liked the challenge, so here it is.
This should do the job no matter how big the triangle is.
<?php
$triangle = array(1,5,11,9,7,3);
$u = 1;
$results = array();
$sumrow =0;
for($i=0; $i<=count($triangle); $i++){
if($i == count($triangle)){
$sumrow += $triangle[0]; // for the last row add the first number of array
}else{
$sumrow += $triangle[$i];
}
if(is_int($u/3)){ // for every third number store results and use the same number again
$i--;
$u = 1;
array_push($results, $sumrow);
$sumrow = 0;
}else{
$u++;
}
}
echo json_encode($results);
?>

Print a new <tr> each time & "N" number of elements inside it, for a total quantity of "Q" [closed]

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 3 years ago.
Improve this question
i have a variable Q,
i want to print "cat" (or whatever) Q times in HTML table rows, only each row of the HTML table can contain maximum of 5 cats.
like if Q <= 5 then i want to print a single <tr>.
& if Q = 10;
then i want to print 2 rows each containing 5 cats.
can someone help me here?
I'm using php as the programming language and HTML.
thanks in advance.
You can also make use of array_chunk to decide the chunk(no. of times) for each row and repeat a string using str_repeat the chunk size times to achieve your goal.
<?php
$times = 12;
$limit_for_each_row = 5;
$string = "Cat";
echo "<table>";
foreach(array_chunk(range(1,$times),$limit_for_each_row) as $chunk){
echo "<tr>" . str_repeat("<td>$string</td>",count($chunk)) . "</tr>";
}
echo "</table>";
Demo: https://3v4l.org/EWgHh
May following code will help you to achieve requested output:
<?php
$print_label = "meow";
$q = 15;
$steps = 5;
echo "<table>";
for($i=1;$i<=ceil($q/$steps);$i++) :
echo "<tr>";
for($j=1;$j<=$steps;$j++) :
echo "<td>".$print_label."</td>";
endfor;
echo "</tr>";
endfor;
echo "</table>";
One way to solve this problem is by using array_fill to make an array of $q copies of the word; array_chunk to split that into the maximum number of words per row; and implode to put all the words in each chunk together into a row:
$word = "cat";
$q = 13;
$row_max = 5;
$words = array_fill(0, $q, $word);
$chunks = array_chunk($words, $row_max);
foreach ($chunks as $chunk) {
echo '<tr><td>' . implode('</td><td>', $chunk) . '</td></tr>' . "\n";
}
Output:
<tr><td>cat</td><td>cat</td><td>cat</td><td>cat</td><td>cat</td></tr>
<tr><td>cat</td><td>cat</td><td>cat</td><td>cat</td><td>cat</td></tr>
<tr><td>cat</td><td>cat</td><td>cat</td></tr>
Demo on 3v4l.org

PHP: How to remove comma in a for loop? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
<?php
for ($i = 10; $i < 101; $i = $i + 10) {
echo $i;
}
?>
I'm starting to learn PHP and this is the code I'm working on. What I'm trying to do is remove the comma on the last item that will display (e.g. 10, 20, 30, 40, 50, 60, 70, 80, 90, 100,) I've searched the forum and all I see are methods for "foreach"...Any suggestions, replies are appreciated.
You could do something like this,
$result = array();
for ( $i = 10; $i < 101; $i = $i + 10 ){
$result[] = $i;
}
echo implode(", ", $result);
This should work!
There is no comma in your code or it's output but your question is still understandable and you just missed posting the code line which outputs those commas. You simply have to check if this is the last iteration of the loop and if so don't print comma
echo $i;
if($i<100) //currently you don't have this check so you get an extra comma
echo ",";
Output
10,20,30,40,50,60,70,80,90,100
Try this:
$result = array();
for ($i = 10; $i < 101; $i += 10) {
$result[] = $i;
}
echo implode(", ", $result);
If it's an array, write implode(',', $array). If it's not, save output from each iteration to a variable(say $output), then, write substr($output,0,-1).
$output = "";
for ($i = 10; $i < 101; $i = $i + 10) {
$output .= $i.",";
}
echo substr($output,0,-1);
Your code doesn't relate to your question/description, though!

Get the amount of elements higher than a particular one [closed]

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 6 years ago.
Improve this question
I have this in my php code:
$aNumbers = array(2,8,9,5.5,4,5.5,6,7,8,9,10,1,'NB');
From this I must determine the amount of values above 5.5 and the average of all numbers combined. Using only a For Loop, if/else construction and the count() function.
I have tried to solve this myself, but nowhere on the internet I can find sufficient information.
This should do it:
$aNumbers = array(2,8,9,5.5,4,5.5,6,7,8,9,10,1,'NB');
const HIGH_VALUE_CUTOFF = 5.5;
$uncleanArrayCount = count($aNumbers);
$cleanArray = array();
$highValueCount = 0;
$sum = 0;
for ($i = 0; $i < $uncleanArrayCount; $i++) {
if ($aNumbers[$i] > 0) { // catch only numbers
$sum += $aNumbers[$i];
$cleanArray[] = $aNumbers[$i]; // builds an array of numbers
}
if ($aNumbers[$i] > HIGH_VALUE_CUTOFF) {
$highValueCount++;
}
}
$average = $sum / count($cleanArray);
echo "Average: $average <br />";
echo "Numbers above " . HIGH_VALUE_CUTOFF . ": $highValueCount";
Next time, post what you've tried. 'Twas fun doing your homework for you!
Try something like this:
<?php
$sum = 0;
$amount = 0;
$aNumbers = array(2, 8, 9, 5.5, 4, 5.5, 6, 7, 8, 9, 10, 1, 'NB');
foreach ($aNumbers as $value){
if($value > 5){
$sum += $value;
$amount++;
}
}
echo "Sum : " . $sum . " - Average : ". ($sum / $amount);
?>

How i can remove point from number using loop function [closed]

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 8 years ago.
Improve this question
I have this codes. My question is How i can remove .1 one from rest of numbers in my output.
Its gives : The counter is 1464.1
I want it to give : The counter is 1464
<?php
$i = 1000;
$t = 10;
while ($i < 100000000) {
echo"<p>The counter is $i";
$i = $i + ($i / $t);
}
?>
And output is :
The counter is 1000
The counter is 1100
The counter is 1210
The counter is 1331
The counter is 1464.1
The counter is 1610.51
Use intval:
echo '<p>The counter is '.intval($i) .'</p>';
EDIT:
Display purposes only use the above code.
Data manipulation use:
$i = intval ($i + ($i / $t));
Use intval():
$i = intval( $i + ($i / $t) );
You can type cast it when you echo it.
echo "<p>The counter is " . (int)$i . "</p>";
You can use:
echo "<p>The counter is ".floor($i)."</p>";
or
echo "<p>The counter is ".intval($i)."</p>";
These will effectively 'cut off' the decimal (or give you the integer value)
or you can round to the nearest integer:
echo "<p>The counter is " . round($i) . "</p>";
OR if you are trying to subtract .1 from your answer (it is unclear in the OP without more examples) you can do this:
echo "<p>The counter is ".($i - .1)."</p>";

Categories