Count elements in a loop - php

I'm trying to count elements in a loop to break each number of elements and show in groups
My little script
$data="house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*";
$exp_filter = explode("*", trim($data));
for ($x = 0; $x <= count($exp_filter); $x++)
{
print "".$exp_filter[$x]."";
if ($x%5 == 0)
{
print "<br>";
}
}
As you can see in the little script each 5 rounds I want show the tag for break and show as in groups of elements.
The problem it´s always show in the first line one element and after this the rest, and no works fine.

The index of $exp_filter starts at 0, so this block of code
if ($x % 5 == 0)
{
print "<br>";
}
should be
if (($x+1) % 5 == 0)
{
print "<br>";
}
Here's the complete modified code
$data = "house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*";
$exp_filter = explode("*", trim($data));
for ($x = 0; $x <= count($exp_filter); $x++)
{
print "".$exp_filter[$x]."";
if (($x + 1) % 5 == 0)
{
print "<br>";
}
}
Working example: http://codepad.org/iEsKK98M

$data="house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*";
$exp_filter=explode("*",trim($data));
for($x=1;$x<=count($exp_filter);$x++)
{
print "".$exp_filter[$x]."";
if($x%5==0)
{
print "<br>";
}
}
Try this. The problem is you started at 0 in for, you should start from 1 ;)

Quickfix:
Demo
<?php
$data="house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*";
$exp_filter=explode("*",trim($data));
for($x=1;$x<=count($exp_filter);$x++)
{
print "".$exp_filter[$x]."";
if($x > 0 && $x%5==0)
{
echo "<br />";
}
}
?>

I would use array chunk and implode instead:
$data="house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*house*";
foreach(array_chunk(explode('*', $data), 5) as $chunk){
echo implode(' ', $chunk) . '<br>';
}
Live example: http://codepad.viper-7.com/ED2wHR

Related

I want to make an arrow that the base width is half of the size of the input

I have this code that works but is missing some details
$input=7;
$k=($input+1)/2;
for($i=1;$i<=$input;$i++){
for($j=1;$j<=$input;$j++){
if($j==($input+1)/2 || $j==$k || $j==$input-$k+1){
echo "*";
}
else{
echo "-";
}
}
echo "<br>";
$k++;
}
And the output look like this
---*---
--***--
-*-*-*-
*--*--*
---*---
---*---
---*---
My desired output is
___*___
__***__
_*****_
*******
__***__
__***__
__***__
In your if statement you have three conditions. So there can only be three stars in a row.
I think your structure is more complex as it should be. You could use str_repeat instead. Something like this:
$input=7;
for($i=1;$i<=$input;$i+=2) {
echo str_repeat('-', ($input - $i) / 2 ) .
str_repeat('*', $i) .
str_repeat('-', ($input - $i) / 2 ) .
'<br>';
}
$shaft = floor($input / 2);
for($i=1;$i<$input/2;$i++) {
echo str_repeat('-', ($input - $shaft) / 2 ) .
str_repeat('*', $shaft) .
str_repeat('-', ($input - $shaft) / 2 ) .
'<br>';
}
The first loop draws the triangle which is growing by 2 each row.
The second loop draws the shaft.
So if you need to do it only using loops and if else, you have to elaborate your if statement. Here's my solution:
$input = 7;
for($i=1;$i<=2*$input;$i+=2) {
for($k=1;$k<=$input;$k++) {
if(($i <= $input && $k > floor(($input - $i)/2) && $k <= ceil(($input + $i)/2)) ||
($i > $input && $k > ceil($input/4) && $k <= floor(3/4*$input))) {
echo "*";
} else {
echo "-";
}
}
echo "<br>";
}
Note: In the first loop I use $i+=2, so with every iteration $i increases by two. To get the right number of lines the loop continues till 2*$input.
The if statement has two parts. In the first part the triangle is drawn (adding two stars every row since $i increases by 2). In the second part, when $i becomes greater than $input, drawing the shaft, which is half the width and 1/4 of the width on each side.
I got the answer guys, thank you all.
$x=($input/2); $y=$x+1; $w=($input/2);
if($w%2==0) {
$w++;
}
for($i=1; $i<=$input; $i++) {
for($j=1; $j<=$input; $j++) {
if($j>=$x && $j<=$y) {
echo "*";
}
else {
echo "_";
}
}
if($i>(($input-1)/2)) {
$x=(($input-$w)/2)+1;
$y=($x+$w)-1;
}
else {
$x--;
$y++;
}
echo "<br>";
}

php First value of array not displaying

I have the following bit of code and for some reason in the first WHILE loop the first value of $actor_list (when $i = 0) does not display. If I simply echo $actor_list[0] then it displays fine, but in the loop it will not display. I merely get [td][/td] as the output. The remaining values of the array display fine.
Also the line
echo '</tr><tr> </br>';
is not displaying.
What am I missing here? The value of $num_actors is an even number in my test scenario so there doesn't seem to be a reason for the above echo line to be skipped.
$actor_list = explode(" ", $actors);
$num_actors = count($actor_list);
if ($num_actors <= 6) {
foreach ($actor_list as $actor) {
echo '[td]'.$actor.'[/td] </br>';
}
} elseif ($num_actors <= 12) {
if ($num_actors % 2 == 0) {
$half_actors = $num_actors / 2;
while ($i <= ($half_actors - 1)) {
echo '[td]'.$actor_list[$i].'[/td] </br>';
$i++;
}
echo '</tr><tr> </br>';
while ($i <= $num_actors) {
echo '[td]'.$actor_list[$i].'[/td] </br>';
$i++;
}
}
}
You're not initialising the variable $i to 0, which means it will be set to 'null' and thus not reference the 0th index of the array; but when it's then incremented its value will become 1.
Note: [..] Decrementing NULL values has no effect too, but incrementing them results in 1.
See: http://php.net/manual/en/language.operators.increment.php
Try adding:
$i = 0;
before the if statement.
Made a few changes.
This is working for me.
Try it out.
<?php
$actor_list = 'act1 act2 act3 act4 act5 act6';
$actors = explode(" ", $actor_list);
$num_actors = count($actor_list);
//debug
//echo "<pre>";
//print_r($actor_list);
//echo "</pre>";
echo "<table>";
if ($num_actors <= 6) {
foreach ($actors as $actor) {
echo '<tr><td>'.$actor.'</td></tr>';
}
} elseif ($num_actors <= 12) {
if ($num_actors % 2 == 0) {
$half_actors = $num_actors / 2;
while ($i <= ($half_actors - 1)) {
echo '<tr><td>'.$actor_list[$i].'</td></tr>';
$i++;
}
while ($i <= $num_actors) {
echo '<tr><td>'.$actor_list[$i].'</td></tr>';
$i++;
}
}
}
echo "</table>";
?>

PHP Loop determine 4th iteration but if the iteration is less than 4 echo something

Heres the scenario, I have array with 7 items and I want to separate them in every fourth iteration.. just like this
$counter2 = 0;
$counter3 = 0;
$counter4 = 0;
$sample_array = array('Aso','Pusa','Daga','Kuting','Tuta','Bubwit','Boom');
foreach($sample_array as $sample_array_value)
{
if(++$counter4 % 4 == 0)
{
echo $sample_array_value;
echo "</div>";
}
elseif(++$counter3 % 3 == 0)
{
echo $sample_array_value;
}
elseif(++$counter2 % 2 == 0)
{
echo $sample_array_value;
}
else
{
echo "<div>";
echo $sample_array_value;
}
}
The out put will be div AsoPusaDagaKuting /div div TutaBubwitBoom
The problem is when it ends in iteration that doesn't count 4 it doesn't give the separator ending..
I need it to output div AsoPusaDagaKuting /div div TutaBubwitBoom /div
Thanks in advance...
You can split it with array_chunk, implode the new subarrays of 4 with array_map, then echo it with implode.
$sample_array = array('Aso','Pusa','Daga','Kuting','Tuta','Bubwit','Boom');
echo "<div>", implode("</div><div>", array_map("implode", array_chunk($sample_array, 4))), "</div>";
Result:
<div>AsoPusaDagaKuting</div><div>TutaBubwitBoom</div>
Try this:
$i = 0;
foreach($sample_array as $sample_array_value)
{
if(++$counter4 % 4 == 0)
{
echo $sample_array_value;
echo "</div>";
}
elseif(++$counter3 % 3 == 0 || ++$counter2 % 2 == 0)
{
echo $sample_array_value;
}
else
{
echo "<div>";
echo $sample_array_value;
}
$i++;
}
if ($i % 4 != 0) {
echo "</div>";
}
You are printing the values inside every condition, then why not use echo once outside any condition? Also you want to close and open a div tag for the forth element, then only 1 counter would do the trick. Only this will work -
$sample_array = array('Aso','Pusa','Daga','Kuting','Tuta','Bubwit','Boom');
$i = 0;
echo "<div>";
foreach($sample_array as $sample_array_value)
{
if($i > 0 && $i % 4 == 0)
{
echo "</div><div>";
}
echo $sample_array_value;
$i++;
}
echo "</div>";
Output
<div>AsoPusaDagaKuting</div><div>TutaBubwitBoom</div>

A Logical Algorithm In PHP

I'm a beginner learning PHP. I have tried to make a loop that has a different behaviour for both even and odd numbers. I've been playing around with it for a while, yet I still can't get it to work. Has anyone got a solution?
$count = 0;
$mod = $count % 2;
while ($count < 10)
{
if ($mod == 0) {
echo "even, ";
} else {
echo "odd, ";
}
$count++;
}
A silly mistake, mod inside while() loop.
$count = 0;
while ($count < 10) {
$mod = $count % 2; //Here
if ($mod == 0) {
echo "even, ";
} else {
echo "odd, ";
}
$count++;
}
$count = 0;
$mod = $count %2;
Is were your problem is.
You have to use the modulus (%) operator inside the for loop. Also, there is no need to store the value from the use of the modulus operator at all, it can be compared directly inside the for-loop.
for ($count = 0; $count < 10, $count++) {
if ($count % 2 == 0) {
echo "even, ";
} else {
echo "odd, ";
}
}
You can also switch the while to a for like this.
Welcome to PHP.
Edit #1:
As you are getting a new value of $count every execution of the for-loop the old value if $count % 2 will be incorrect. It has to recalculate for every $count. First it checks if 0 is divisible by 2, then onto 1 and so forth. For every value of $count you have to check the divisibility.
In most programming languages you aren't computing a variable onto another, instead you are taking the value of the variable. Like $a = $b + $c; in that case, if you change the value of $b or $c it does not automatically update $a. Instead you have to call $a = $b + $c again. It is the same with % operator.
$count = 0;
while ($count < 10) {
$mod = $count % 2;
if ($mod == 0) {
echo "even, ";
} else {
echo "odd, ";
}
$count++;
}
use for loop instead of while loop
for($count=0;$count<10;$count++)
{
if(($count % 2) == 0)
echo "even,";
else
echo "odd,";
}

If value is greater/lesser than xyz

I have a value as a number. For instance, 502.
I want to write a php if statement that will display some text if the value is lesser or greater than certain numbers, or between a range.
E.g.
number is 502, text will say: "Between 500-600"
number is 56, text will say: "Between 0-60"
etc.
So far I have this:
<?php $count=0;?>
<?php $board = getUserBoard($userDetails['userId']);?>
<?php if(is_array($board)):?>
<?php $boardCount = count($board);?>
<?php foreach($board as $key=>$value):?>
<?php
$boardPin = getEachBoardPins($value->id);
$count = $count + count($boardPin);
?>
<?php endforeach?>
<?php endif?>
And that gives me a number:
<?php echo $count;?>
I have tried writing...
<?php if(($count)): => 500 ?>
Over 500
<?php endif ?>
But I keep running into errors.
I'd like to create a list if possible with elseif statements denoting various number ranges.
E.g.
0-50, 51-250, 251-500 etc.
Can anyone help me?
Thanks.
The sanest, neatest and most widely used syntax for if conditions in PHP is:
if($value >=500 && $value <=600 )
{
echo "value is between 500 and 600";
}
if ($count >= 0 && $count < 100) {
echo 'between 0 et 99';
} elseif ($count < 199) {
echo 'between 100 and 199';
} elseif { ...
}elseif ($count < 599) {
echo 'between 500 and 599';
} else {
echo 'greater or equal than 600';
}
I wrote something like this a few years back (might be a better way to do it):
function create_range($p_num, $p_group = 1000) {
$i = 0;
while($p_num >= $i) {
$i += $p_group;
}
$i -= $p_group;
return $i . '-' . ($i + $p_group - 1);
}
print 'The number is between ' . create_range(502, 100) . '.';
It'll say 500-599, but you can adjust it to your needs.
I'm not sure what you need, but here is what I understand you ask:
function getRange($n, $limit = array(50, 250, 500)) { // Will create the ranges 0-50, 51-250, 251-500 and 500-infinity
$previousLimit = 0;
foreach ($limits as $limit) {
if ($n < $limit) {
return 'Between ' . ($previousLimit + 1) . ' and ' . $limit; //Return whatever you need.
}
$previousLimit = $limit;
}
return 'Greater than ' . $previousLimit; // Return whatever you need.
}
echo getRange(56); // Prints "Between 51 and 250"
echo getRange(501); // Prints "Greater than 500"
echo getRange(12, array(5, 10, 15, 20)); // Prints "Between 11 and 15"
function getRange($number){
$length=strlen($number);
$length--;
$r1=round($number,-$length);
if ($r1>$number){
$r2=$r1-pow(10,$length);
return ''.$number.' value is between '.$r2.'-'.$r1;
}
else {
$r2=$r1+pow(10,$length);
return ''.$number.' value is between '.$r1.'-'.$r2;
}
}
Try this.

Categories