how can I use for loop - php

i just want ask how i can use for loop to print
123
456
i'm try with this code:
<?php
$a = array(1,2,3,4,5,6);
foreach($a as $r){
for($q = 0; $q < 3; $q++) {
echo $r;
}
echo "<br />";
}
?>
But the problem is, it prints:
111
222
333
444
555
666

You're printing the value of $r three times for each value of $r; what you want is to print each value and print a break after every third.
Something like this would work:
foreach ($a as $i => $r) {
echo $r;
// insert break after every third value
if ($i > 0 && ($i + 1) % 3 == 0) {
echo '<br />';
}
}
Or, you could use array_chunk() to split the array up in chunks of three and print each of those.
foreach (array_chunk($a, 3) as $chunk) {
foreach ($chunk as $nr) {
echo $nr;
}
echo '<br />';
}

Use array_chunk($a, 3) and then use implode , that will give you required result.

$a = array(1,2,3,4,5,6,7,8,9);
$result='';
$i = 1;
foreach($a as $r)
{
$result.=$r;
if($i%3 == 0)
{
echo $result."<br />";
$result='';
}
$i++;
}

Related

get the output of array in deciending order using php

i have one php array
and i want to draw output of this array in something like deciding type.
Here is my php code
<?php
$data = array('A','B','C','D','E','F');
$count = count($data);
for($k = 0;$k<$count;$k++){
foreach($data as $key => $value){
if($key == $k){
$datanew = $count - $k;
for($i=0 ; $i<$datanew ; $i++){
echo "X";
}
}else{
echo "V";
}
}
echo "</br>";
}
?>
current output
XXXXXXVVVVV
VXXXXXVVVV
VVXXXXVVV
VVVXXXVV
VVVVXXV
VVVVVX
excepted output
XXXXXX
VXXXXX
VVXXXX
VVVXXX
VVVVXX
VVVVVX
insort
after X no V
what logic i want to implicit to get perfect output.
thanks
I hope you're happy with the following solution:
<?php
$data = array('A', 'B', 'C', 'D', 'E', 'F');
$count = count($data);
for ($k = 0; $k < $count; $k++) {
echo str_repeat("V", $k);
echo str_repeat("X", $count-$k);
echo "<br />";
}
?>
I used str_repeat to repeat the chars X and V. So you just need only one for-loop.
Output:
XXXXXX
VXXXXX
VVXXXX
VVVXXX
VVVVXX
VVVVVX
Example on Ideone.com
Simple just add break in your code as below:
<?php
$data = array('A','B','C','D','E','F');
$count = count($data);
for($k = 0;$k<$count;$k++){
foreach($data as $key => $value){
if($key == $k){
$datanew = $count - $k;
for($i=0 ; $i<$datanew ; $i++){
echo "X";
}
break;
}
else{
echo "V";
}
}
echo "</br>";
}
?>
And output as you wanted

How can I print integer in triangle form

I want to print integer in triangle form which look like this
1
121
12321
I tried this but I do not get the actual result
for($i=1;$i<=3;$i++)
{
for($j=3;$j>=$i;$j--)
{
echo " ";
}
for($k=1;$k<=$i;$k++)
{
echo $k;
}
if($i>1)
{
for($m=$i; $m>=1; $m--)
{
echo $m;
}
}
echo "<br>";
}
Output of this code is:
1
1221
123321
Where am I going wrong, please guide me.
Another integer solution:
$n = 9;
print str_pad ("✭",$n," ",STR_PAD_LEFT) . PHP_EOL;
for ($i=0; $i<$n; $i++){
print str_pad ("", $n - $i);
for ($ii=-$i; $ii<=$i; $ii++){
if ($i % 2 != 0 && $ii % 2 == 0)
print "&#" . rand(10025,10059) . ";";
else print $i - abs($ii) + 1;
}
print PHP_EOL;
}
✭
1
1✬1
12321
1❊3✪3✳1
123454321
1✼3✶5❃5❈3✸1
1234567654321
1✾3✯5✿7❉7✫5✷3✶1
12345678987654321
Or if you already have the string, you could do:
$n = 9; $s = "12345678987654321"; $i = 1;
while ($i <= $n)
echo str_pad ("", $n-$i) . substr ($s,0,$i - 1) . substr ($s,-$i++) . PHP_EOL;
Your code should be this:
for($i=1;$i<=3;$i++)
{
for($j=3;$j>$i;$j--)
{
echo " ";
}
for($k=1;$k<$i;$k++) /** removed = sign*/
{
echo $k;
}
if($i>=1) /**added = sign*/
{
for($m=$i; $m>=1; $m--)
{
echo $m;
}
}
echo "<br>";
}
Try this.
Details:
Your loop is not proper as in case of for($k=1;$k<=$i;$k++), this will print the
repeated number when check the condition for less then and again for equals to.
So remove the equals sign.
reason to add the eqaul sign in if($i>=1) is that the first element will not print if there will not be equals as first it will be print by for loop from where removed the equal sign.
Your output will be this:
1
121
12321
For all the x-mas lovers:
$max = 9; # can be 2 .. 9
for($i = 1; $i <= $max; $i++) {
$line = (str_pad('', $max - $i));
for($ii = 1; $ii <= $i; $ii++) {
$line .= $ii;
}
for($ii = $i-1; $ii > 0; $ii--) {
$line .= $ii;
}
echo $line . PHP_EOL;
}
Output:
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
Amazing what computers are able to achieve nowadays! Isn't it?
A little late to the party, but here's yet another solution that uses a "for" loop with two initialization variables and a ternary-based incrementer/decrementer. It's an unorthodox use of a "for" loop, but it's still perfectly valid and arguably makes the code more elegant and easier to follow. I chose to add space before and after each semicolon and omit all other space inside the parentheses so it's easier to visualize each of the three pieces of the "for" loop (initialization, condition, increment/decrement):
$count = 9;
echo "<pre>";
for ($i=1; $i<=$count; $i++) {
echo str_pad("",$count-$i," ",STR_PAD_LEFT);
for ( $j=1,$up=true ; $j>0 ; $up?$j++:$j-- ) {
echo $j;
if ($j==$i) {$up = false;}
}
echo "<br>";
}
echo "</pre>";
Output:
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321

PHP Loop: Every 4 Iterations Starting From the 2nd

I have an array that can have any number of items inside it, and I need to grab the values from them at a certain pattern.
It's quite hard to explain my exact problem, but here is the kind of pattern I need to grab the values:
No
Yes
No
No
No
Yes
No
No
No
Yes
No
No
I have the following foreach() loop which is similar to what I need:
$count = 1;
foreach($_POST['input_7'] as $val) {
if ($count % 2 == 0) {
echo $val;
echo '<br>';
}
$count ++;
}
However, this will only pick up on the array items that are 'even', not in the kind of pattern that I need exactly.
Is it possible for me to amend my loop to match that what I need?
You can do this much simpler with a for loop where you set the start to 1 (the second value) and add 4 after each iteration:
for ($i = 1; $i < count($_POST['input_7']); $i += 4) {
echo $_POST['input_7'][$i] . '<br />';
}
Example:
<?php
$array = array(
'foo1', 'foo2', 'foo3', 'foo4', 'foo5',
'foo6', 'foo7', 'foo8', 'foo9', 'foo10',
'foo11', 'foo12', 'foo13', 'foo14', 'foo15'
);
for ($i = 1; $i < count($array); $i += 4) {
echo $array[$i] . '<br />';
}
?>
Output:
foo2foo6foo10foo14
DEMO
Try this:
$count = 3;
foreach($_POST['input_7'] as $val) {
if ($count % 4 == 0) {
echo $val;
echo '<br>';
}
$count ++;
}

Add static number in the for loop index with PHP

I have following for loop code in PHP
for($i=10; $i<=50; $i=$i+10)
{
echo $i;
}
it will print
10 20 30 40 50
I want to add some specific $i value such as
$i=15 and $i=28
So it shold print
10 15 20 28 30 40 50
How should I edit the code ?
If you want specific values, you should make an array with those values and iterate through it:
$vals = array(10, 15, 20, 28, 30, 40, 50);
foreach ($vals as $i) {
echo $i;
}
if you have fixed place where to show these values .. then you can use simple if
for($i=10; $i<=50; $i=$i+10)
{
echo $i;
if($i == 10)
{
echo '15';
}
if($i == 20)
{
echo '28';
}
}
Ok, i'll play the "interview question" game :
for($i=10; $i<=50; $i++) {
if ($i % 10 === 0) {
echo $i;
}
else if ($i === 15 || $i === 28) {
echo $i;
}
}
Result at http://codepad.org/JBPkm8W1
You can improve this answer by adding an "allowed values" table :
$allowed = array (15, 28); // List here all the non % 10 value you want to print
for($i=10; $i<=50; $i++) {
if ($i % 10 === 0) {
echo $i;
}
else if (in_array($i, $allowed)) {
echo $i;
}
}
The result at http://codepad.org/w8Erv17K
The easiest way is to use a foreach loop like #WaleedKhan wrote.
To prepare the array you can use for loop like you did:
$vals = array();
for($i = 10; $i <= 50; $i = $i + 10){
$vals[] = $i;
}
$vals[] = 15;
$vals[] = 28;
sort($vals);
foreach(...
Try this :
$extra = array(15,28);
$res = array();
for($i=10; $i<=50; $i=$i+10){
$res[] = $i;
}
$result = array_merge($res,$extra);
sort($result);
echo "<pre>";
print_r($result);
You can put the 15 and 28 values in array and get the values using array_intersect.
Create an array to hold the 15 and 28 values (intermeditate values).
$new_vals = array(15,28);
Now in your for loop you can call array_insersect function to get the intermediate values. Your final code will look like this.
$new_vals = array(15,28);
for($i=10; $i<=50; $i=$i+10)
{
echo $i;
$val_range = range($i,$i+10);
$new_array = array_intersect($new_vals , $val_range);
foreach($new_array as $value)
{
echo $value;
}
}
You could do something like this:
function EchoLoopStuff($start, $to, $step) {
for($i=$start; $i<=$to; $i=$i+$step) {
echo $i;
}
}
But you'd need to add some checking to save yourself from issues when inputs contradict.

Continue foreach loop from middle

I have this for each loop:
foreach($downloads as $dl) {
echo seosvelniau2($dl['title']);
}
By default it gives me 50 results, is there any way to split this foreach loop into two (1-25) and (26-50), so I can put both into two separate table columns?
I know, that i can make loop to show only first 25 results like this:
$i=0;
foreach($downloads as $dl) {
$i++;
echo seosvelniau2($dl['title']);
if ($i == 25)
break;
}
but how to do second loop to show (26-50) results?
You can divide the array $downloads even before the loop.(using array_chunk)
$Chunks = array_chunk($downloads , 25);
foreach($Chunks[0] as $dl)
{
//Group 1
}
foreach($Chunks[1] as $dl)
{
///Group2
}
EDIT: Here's a general example: (In case you have more than 50 elements)
$Chunks = array_chunk($downloads , 25);
foreach($Chunks as $oneChunk)
{
//New group of 25 elements.
foreach($oneChunk as $dl)
{
}
}
Two different approaches:
Use each to iterate over the array.
$i = 0;
while(list($id, $item) = each($array)) {
echo $item;
if (++$i == 25) { break; }
}
while(list($id, $item) = each($array)) {
echo $item;
}
If you don't need that array after the loop is complete, you can simply shift the items:
$i = 0;
while (++$i < 25 && count($array)) {
$item = array_shift($array);
echo $item;
}
foreach ($array as $item) {
echo $item;
}
You could switch the columns in between:
$i = 0;
foreach ($downloads as $dl) {
if (++$i === 25) echo '</tr><tr>';
echo seosvelniau2($dl['title']);
}
Another option:
$i=0;
foreach($downloads as $dl) {
$i++;
if ($i <= 25){
//first 25
}else{
//rest
}
}
If you're in the process if drawing an HTML table, and you need to switch td, just do something like this:
for ( $i = 0; $i < count( $downloads ); $i++ )
{
echo seosvelniau2( $downloads[ i ][ 'title' ] );
if ( $i % 25 == 0 )
{
echo( '</td><td>' );
}
}
This will create a new columns every 25 values.
Wouldn't you just use a normal for loop instead of foreach? Then you can determine the start and end points manually, like so.
Then you should have something more or less like this:
for ($i=1; $i<=25; $i++)
{
echo "The number is " . $i . "<br />";
}
for ($i=26; $i<=50; $i++)
{
echo "The number is " . $i . "<br />";
}

Categories