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.
Related
I don't have any idea if how I am going to print a pattern, only if I input the number of row and column, help me guys, send your code
<?php
if (isset($_GET['row']) && $_GET['column']) {
$row = $_GET['row'];
$column = $_GET['column'];
$output ="*";
for ($i=$_GET['row']; $i <=1 ; $i++) {
for ($j=$i; $j <=$_GET['column']; $j++) {
$count = $i;
if ($i == $j) {
echo $count. " ";
}else{
echo $count +=4;
} echo "<br>";
}
}
}
?>
here is what I want to have
Enter Row : 5
Enter Column : 4
Output:
*****
*****
*****
*****
You can try the following way with the help of array_fill() and implode(). The array_fill() function fills an array with values of * here and implode() join the stars to a single string.
// $_GET = ['row' => 5, 'column' => 4];
if (isset($_GET['row'], $_GET['column']) && $_GET['row'] > 0 && $_GET['column'] > 0) {
for($i = 0; $i < $_GET['row']; $i++) {
echo implode('', array_fill(0, $_GET['column'], '*')) . PHP_EOL;
}
}
Working demo.
<?php
$count=count($admissions);
$divide=$count/3;
$divide=round($divide);
foreach($admissions as $key => $row)
{
if(//First Part )
{
echo "Alpha";}
else if(//2nd Part )
{
echo "Beta";
}else
{
echo "Gamma";
}
}
?>
I have a dynamic array list and i want to divide it equally in 3 parts.
if Count of array is 30.
So i want to echo for first 10 record
echo "Alpha";
Second 10 Records
Echo "Beta";
3rd 10 Records
Echo "Gamma";
if array size is 60 then it will be divided into 20 parts each.
How can i echo the alpha, beta and gamma.
I thing your question is about if conditions. So you can use this code:
$count=count($admissions);
$divide=$count/3;
$divide=round($divide);
$i = 1;
foreach($admissions as $key => $row)
{
if($i > 0 && $i <= $divide)
{
echo "Alpha";
}
else if($i > $divide && $i <= ($divide*2))
{
echo "Beta";
}
else //equal else if($i > $divide*2 )
{
echo "Gamma";
}
$i++;
}
Try using a normal for loop :
For ($i = 0; $i < $count ; $i++){
echo "alpha";
}
For ($i = $count; $i < 2*$count ; $i++){
echo "beta";
}
For ($i = 2*$count; $i < 3*$count ; $i++){
echo "gamma";
}
Try this hope you are expecting this. According to the requirement which you specified in comments.
Try this code snippet here
<?php
ini_set('display_errors', 1);
$range=range(0,12);
$result=array_chunk($range, 4);
if(count($result[count($result)-1])!=4)
{
$temp=$result[count($result)-1];
unset($result[count($result)-1]);
$result[count($result)-1]=array_merge($result[count($result)-1],$temp);
}
print_r($result);
Let's have an array of three elements and play with the modulo:
<?php
$count=count($admissions);
$divide=$count/3;
$divide=round($divide);
$divisions = array(0 => array(), 1 => array(), 2 => array())
$modulo = 0;
foreach($admissions as $key => $row)
{
$divisions[($modulo + 1) % 3][$key] = $row;
}
This will do the partitioning you need.
I want to create a loop in php which start again from 1 after reaching a specific number assigned in variable.
Loop has to run 10 time
But after reaching 5 as i++ i want this loop to start again from 1 something as given below.
1,2,3,4,5,1,2,3,4,5
Please help!!
You might want to use the modulo operator, %. This will cause numbers to "cycle" like what you want.
for ($i = 0; $i < 10; $i++) {
echo ($i % 5) + 1;
}
The above will print out the numbers 1 through 5 twice.
Try -
$count = 0;
for ($i = 1 ; $i <= 10; $i++) {
$count++;
echo $count;
if ($count == 5) {
$count = 0;
echo "</br>";
}
}
Try this:
$i=1;
while($i<=10)
{
echo $i;
$i++;
if($i>5)
{
$i=1;
echo "</br>";
}
}
You can try this:-
$count = 10;
for ($i = 0; $i < $count; $i++)
{
if($i != ($count-1)){$coma = ',';}else{$coma = '';}
$value = ($i % 5)+1;
$output = $value.$coma;
echo $output;
}
Output:- 1,2,3,4,5,1,2,3,4,5
<?php
$loop=1;
for($i=1;$i<=10;$i++)
{
echo $loop;
if($i==5)
{
$loop=0;
echo "</br>";
}
$loop++;
}
?>
Output:
12345
12345
This can be achieved without using loop also please find the below 2 functions helpful
First:
function createDateRangeArray($strDateFrom,$strDateTo)
{
// takes two dates formatted as YYYY-MM-DD and creates an
// inclusive array of the dates between the from and to dates.
// could test validity of dates here but I'm already doing
// that in the main script
$aryRange=array();
$iDateFrom=mktime(1,0,0,substr($strDateFrom,5,2), substr($strDateFrom,8,2),substr($strDateFrom,0,4));
$iDateTo=mktime(1,0,0,substr($strDateTo,5,2), substr($strDateTo,8,2),substr($strDateTo,0,4));
if ($iDateTo>=$iDateFrom)
{
array_push($aryRange,date('Y-m-d',$iDateFrom)); // first entry
while ($iDateFrom<$iDateTo)
{
$iDateFrom+=86400; // add 24 hours
array_push($aryRange,date('Y-m-d',$iDateFrom));
}
}
return $aryRange;
}
Second:
$st_date = '2012-07-20';
$ed_date = '2012-07-27';
$dates = range(strtotime($st_date), strtotime($ed_date),86400);
$range_of_dates = array_map("toDate", $dates);
print_r($range_of_dates);
function toDate($x){return date('Y-m-d', $x);}
These 2 functions will be returning you the dates between the 2 dates you will pass and then you can loop on the output array to perform operations
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 ++;
}
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 />";
}