php array is printed infinite time using while loop - php

I know i Can easily do this with a for loop but i am trying to do it in while loop and I get Google infinite times. Why is this? I Knew something was wrong however because i was going over a tutorial on tuts+ I thought it was my mistake. Then I read the comments section of the video and the instructor says sorry I forgot to increment the I.
$month = array('google', 'html5nurse' , 'facebook');
$i = 0;
while ( $i < 10) {
echo "<li>$month[$i]</li>";
}
?>

Add i++ after the echo statement.
$month = array('google', 'html5nurse' , 'facebook');
$i = 0;
while ( $i < 10) {
echo "<li>$month[$i]</li>";
$i++;
}

It happens because $i is always equal to 0 in your code.
You need to increment it (as stated in the other solution) for instance using $i++ in the loop.
Note that it's generally better to use foreach which will iterate over each element of the array:
$months = array('google', 'html5nurse' , 'facebook');
foreach($months as $month){
echo $month."<br/>";
}

$month = array('google', 'html5nurse' , 'facebook');
$i = 0;
while ( $i++ < 10)
{
echo "<li>$month[$i]</li>";
}
?>

You should be using $i++ to increment $i and also using count so that the loop does not continue after there are no more results in the array.
<?php
$month = array('google', 'html5nurse' , 'facebook');
$i = 0;
$count = count($month);
while ($i < $count)
{
echo "<li>$month[$i]</li>";
$i++;
}
?>

Related

For loop (php) that results in this: 12345678910987654321

My niece is trying to create one for-loop (php), that results in this:
* 12345678910987654321
example for loop she tried:
for ($i = 1; $i <= 10; $i++ , $i = 10; $i <= 1; $i--) {
echo $i . ' ';
}
She can only use if's and elseif's. I'm not a programmer and can't really help her. Any ideas how this could be achieved in php?
Any information would be greatly appreciated.
The key is to add a variable instead of a number, then reverse that number when $i hits 10.
for($i = 1, $j = 1; $i> 0; $i+=$j) // Start i at 1, and j at 1
{
echo $i;
if($i == 10)
$j = -1; // i has hit 10, so use -1 to start subtracting
}
Another possibility is to loop up to 20, printing $i for the ascending part and 20 - $i for the descending.
for ($i = 1; $i < 20; $i++) {
if ($i <= 10) {
echo $i;
} else {
echo 20 - $i;
}
}

Declaring a variable dynamically in PHP

I need some variables in the following format:
$m_01;
$m_02;
$m_03;
.....
.....
.....
$m_12;
The digits in the variables are the months of the calendar.
I can declare 12 variables separately. However, I want to declare the variable using a loop. So I did something like this.
for($i = 1; $i <= 12; $i++) {
if($i<10)
$month = '0'.$i;
else
$month = $i;
$m_$i;
}
However, I am getting some error:-
Parse error: syntax error, unexpected '$month' (T_VARIABLE) in /var/www/html/custom/ci/Dotell_customer/application/controllers/login.php on line 412
How can I overcome this issue?
NOTE:
$$month creates a variable 01;
Is there any way where I can cave variable m_01?
P.S. I am aware of array. I just want to learn PHP variables variables.
This is not the best practise to follow, but still just for the answer:
for($i = 0; $i <= 12; $i++) {
${"m_$i"} = $i;
}
echo $m_1;
echo $m_2;
echo $m_3;
The best practise would be to create an array. For eg:
$arr = [];
for( $i=0; $i <=12; $i++ ) {
$arr['m_'.$i] = $i;
}
print_r($arr);
I think you are looking for something like
$varname = 'm_'.$i; // format the way you need it
$$varname = ...
As noted in the comments, it's rather a code smell, and often unnecessary. Typically an array does a better job, i.e.
$m[$i] = ...
Use PHP variable variables. This works as also suggested in the comments
${"m_$i"}
Going with Davids suggestion of using an array.
$month = [];
for($i = 1; $i <= 12; $i++)
{
if($i<10)
$month[] = '0'.$i;
else
$month[] = $i;
$month[$i];
}
here the $var[] = ... syntax appends your array. the $month[$i] accesses it.
Use of double variable is not usually suggested. You should really use an array to solve your problem as:
$month = array();
for($i = 1; $i <= 12; $i++)
{
if($i<10)
$month['m_0'.$i] = $i;
else
$month['m_'.$i] = $i;
}
otherwise if you really want to necessary go for double variable then :
for($i = 1; $i <= 12; $i++)
{
if($i<10)
${"m_0$i"} = $i;
else
${"m_$i"} = $i;
}
I hope it helps
for($i = 1; $i <= 12; $i++){
if($i<10)
$month = '0'.$i;
else
$month = $i;
$month = 'm_' . $month;
..........
}
Access var as
assignment $month = 'm_12';
value $$month

How to use a variable in an array request in php

Im using
$i = 0;
while ($i <= 6) {
print $game['stats']['item0'];
$i++;
}
I want the item0 to increment to item1 up to item6, so the last while should be
print $game['stats']['item6'];
I also tried: $game['stats']['item{$i}'] but it doesn't work.
Any Ideas for me?
If you need to do something a set number of times, a for loop is generally more concise than a while loop.
for ($i=0; $i < 6; $i++) {
print $game['stats']["item$i"];
}
It isn't a more correct way of doing it, it really just depends on your style, but I thought it was worth mentioning.
You can try this:
while ($i <= 6) {
$key = 'item'.$i;
print $game['stats'][$key];
$i++;
}
You should be good to go with this
$i = 0;
while ($i <= 6) {
print $game['stats']["item$i"];
$i++;
}
When a string is specified in double quotes or with heredoc, variables
are parsed within it.
Include the $i at the end of the string :
<?php
$i = 0;
while ($i <= 6) {
print $game['stats']['item' . $i]; //<============== , 'item0', 'item1', ...
$i++;
}
?>
You have to append $i after item. And you don't need to define new variable.
$i = 0;
while ($i <= 6) {
print $game['stats']['item'.$i];
$i++;
}
Here's an edited version of your code. It should work:
<?php
$i = 1;
$game = array("stats" =>
array("item1" => 1, "item2" => 2, "item3" => 3, "item4" => 4, "item5" => 5, "item6" => 6 ));
while ($i <= 6) {
$tmp = 'item'.$i;
print $game['stats'][$tmp];
$i++;
}

Function call to set variable doesn't work

the following code is modified after suggestion does get the $i $j works well
<?php
$i=1;
$j=1;
function fixIndex() {
global $i, $j;
$a=$j-$i;
if ($a === 60){
$i += 60;
}
$j++;
}
but it does not work on my main code as follow:
$times = array();
$values1 = array();
$values2 = array();
$values3 = array();
$values4 = array();
$i=1;
$j=1;
$file_lines = file($DispFile, FILE_IGNORE_NEW_LINES|FILE_SKIP_EMPTY_LINES);
foreach( $file_lines as $line_num => $line_value) {
fixIndex();
if ($line_num < $i)continue; // skip records in 60* range
$line_elements = explode(",", $line_value);
$times[] = date("H:i:s", $line_elements[0]);
$values1[] = $line_elements[1];
$values2[] = $line_elements[2];
$values3[] = $line_elements[3];
$values4[] = $line_elements[4];
}
After the foreach loop I call for the fixIndex(), trying to get the $i value for the next line of code(if ($line_num < $i)continue;) to skip 60 records before i build an array. That $i doesn't seem to skip the record. If I change that $i to a number on it ($line_num < 60 )continue; Than it does skip the 60 records.
also is there any change of the program flow if this php program do a refresh on the every 10 sec on the web, What I mean is did $i and $j rest to 1 every time after refresh?
Thanks again to anyone for any help
You can use pass by reference to avoid needing global variables here. What that means is the function will modify the variables that were passed to it.
https://secure.php.net/manual/en/language.references.pass.php
<?php
function fixIndex(&$i, &$j) {
global $i, $j;
if ($j - $i == 5) {
$i += 5;
}
$j++;
}
$i=1;
$j=1;
for ($k=0;$k<=20; $k++){
fixIndex($i, $j);
echo $i.'<br />';
echo $j.'<br />';
}
?>
Also, I changed "$i + 5" (which doesn't make anything happen) to "$i += 5" so that it modifies the variable $i.
You are not storing your incremented value of $i.
<?php
$i=1;
$j=1;
function fixIndex() {
global $i, $j;
if ($j - $i == 5){
$i = $i+5;
}
$j++;
}
for ($k=0;$k<=20; $k++){
fixIndex();
echo $i.'<br />';
echo $j.'<br />';
}
Demo : https://eval.in/518511
You probably could describe what you want to do like this:"increment $i by 5 every time $j has grown by 5".This could be implemented in a straight and very compact form like this.(The solution covers all cases, and is not depending on the upper limit of the iteration.)
<?php
function fixIndex(&$i,$j) {
if ( ($j>1) && (($j-1) % 5 == 0) ) $i += 5;
}
$i = 1;
for ($j=1;$j<=20; $j++){
fixIndex($i,$j);
echo "\$j=$j, \$i=$i <br />";
}
Notes:
( ($j-1) % 5 == 0 )
…means: when $j -1 can be devided by 5 without a remainder (% 5 = "modulo 5").
function fixIndex(&$i,$j)
&$i means that a reference (pointer) to the memory of the $i variable is accepted instead of its value. This is necessary since the function is modifying the value of $i. So, you would not need the global statement.On the other hand the $j variable is not modified and thus can be accepted as a value.
Result:
$j=1, $i=1
$j=2, $i=1
$j=3, $i=1
$j=4, $i=1
$j=5, $i=1
$j=6, $i=6
$j=7, $i=6
$j=8, $i=6
$j=9, $i=6
$j=10, $i=6
$j=11, $i=11
$j=12, $i=11
$j=13, $i=11
$j=14, $i=11
$j=15, $i=11
$j=16, $i=16
$j=17, $i=16
$j=18, $i=16
$j=19, $i=16
$j=20, $i=16

Php loop not showing me result of operation but no errors

for ($i= count($words); $i < count($words) -1 ; $i++) {
$w = strtolower(array_values($words)[$i]);
$s = array_map('strtolower',$string_to_search);
if (in_array($s , $w)) {
echo $w;
echo "im here";
}
}
The code above is supposed to check if a word is in an array and if so count it. Im not getting errors but I cant see results please help
Ive tried the foreach loop but its not working aswell
Can someone please tell me where im messing up im a noob in php
start this loop with for ($i = 0; because when you start from count, it is not iterating at all:
for ($i= 0; $i <= count($words) -1 ; $i++) {
Change your code to be as follows:
for ($i= 0; $i < count($words) -1 ; $i++) {
$w = strtolower(array_values($words)[$i]);
$s = array_map('strtolower',$string_to_search);
if (in_array($s , $w)) {
echo $w;
echo "im here";
}
}

Categories