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
Related
Why this piece of code works when it is clearly wrong in the second for loop (for ($i==0; $i<$parts; $i++) {)?
Does php allows for multiple comparisons inside for loops?
function split_integer ($num,$parts) {
$value = 0;
$i = 0;
$result = [];
$modulus = $num%$parts;
if ($modulus == 0) {
for($i = 0; $i < $parts; $i++)
{
$value = $num/$parts;
$result[] = $value;
}
} else {
$valueMod = $parts - ($num % $parts);
$value = $num/$parts;
for ($i==0; $i<$parts; $i++) {
if ($i >= $valueMod) {
$result[] = floor($value+1);
} else {
$result[] = floor($value);
}
}
}
return $result;
}
Code for ($i==0; $i < $parts; $i++) runs because $i==0 has no impact on loop.
In normal for loop first statement just sets $i or any other counter's initial value. As you already set $i to 0 earlier, your loop runs from $i = 0 until second statement $i < $parts is not true.
Going further, you can even omit first statement:
$i = 0;
for (; $i < 3; $i++) {
echo $i;
}
And loop will still run 3 times from 0 to 2.
Here is my code, and it is not removing $arr[5] element so that I am trying to remove strings starting with # from my array
this is code
<?php
$arr = [
'#EXTM3U',
'#EXTINF:177,Paul Dateh & Oren Yoel - Be More',
'Be More.mp3',
'#EXTINF:291,Christopher Toy - Just Because',
'Just Because.mp3',
'#EXTINF:238,Magnetic North - Drift Away',
'Drift Away.mp3'
];
for ($i = 0; $i <= count($arr); $i++) {
if ($arr[$i]{0} == '#') {
echo $arr[$i] . "\n";
unset($arr[$i]);
}
}
print_r($arr);
?>
Reason:- You are counting array length inside the loop and every time when any value got unset() from the array, length of array decreased and value of count($array) changed (simply decreased)
So logically your 5th and 6th element never goes through if condition (they never get traversed by loop because of decreasing length of the array )
Solution 1:- Put count outside and it will work properly:-
$count = count($arr);
//loop start from 0 so use < only otherwise, sometime you will get an undefined index error
for ($i = 0; $i < $count; $i++) {
if ($arr[$i]{0} == '#') {
//echo $arr[$i] . "\n";
unset($arr[$i]);
}
}
print_r($arr);
Output:-https://eval.in/996494
Solution 2:- That's why i prefer foreach() over for() loop
foreach($arr as $key=> $ar){
if ($ar[0] == '#') {
unset($arr[$key]);
}
}
print_r($arr);
Output:-https://eval.in/996502
more spacific :
for ($i = 0; $i < count($arr); $i++) {
if (strpos($arr[$i], '#') !== false) {
echo "<br/>";
} else {
echo $arr[$i]."<br/>";
}
}
Try to use additional array to push right values. You calc count($arr); each iteration and when you do count($arr); your array gets smaller and count($arr); returns smaller values, so last elements won't be comparing, try to use variable to calc count before loop make changes:
<?php
//...
$start_count = count($arr);
for ($i = 0; $i <= $start_count; $i++) {
if ($arr[$i]{0} == '#') {
echo $arr[$i] . "\n";
unset($arr[$i]);
}
}
Or remove bad element with a help of additional array, put good elements in new array and don't delete them from input array:
<?php
$arr = [
'#EXTM3U',
'#EXTINF:177,Paul Dateh & Oren Yoel - Be More',
'Be More.mp3',
'#EXTINF:291,Christopher Toy - Just Because',
'Just Because.mp3',
'#EXTINF:238,Magnetic North - Drift Away',
'Drift Away.mp3'
];
$cleared_from_mess_array = array();
for ($i = 0; $i <= count($arr); $i++) {
if ($arr[$i]{0} != '#')
{
array_push($cleared_from_mess_array,$arr[$i]);
}
}
print_r($cleared_from_mess_array);
exit;
I have written the following code to count the number of string occurrences in a given file.
PHP
<?php
$p = fopen("g.txt", "r");
$q = fread($p, filesize("g.txt"));
$t = explode(" ", $q);
$m = explode(" ", $q);
$i = 0;
$j = 0;
$r = 0;
$count = 0;
$c = count($t);
$d = array();
echo "count of".
"<br/>";
for ($i = 0; $i < $c; $i++) {
for ($j = $i; $j < $c; $j++) {
if ($t[$i] == $t[$j]) {
$count = $count + 1;
}
}
for ($r = $i + 1; $r < $c; $r++) {
if ($t[$i] == $t[$r])
unset($t[$r]);
}
echo $t[$i].
"=".$count.
"<br/>";
$count = 0;
}
?>
I am getting a notice of undefined offset on line numbers 17 and 24, though my output is coming out to be correct. Can you please help me in rectifying the above problem?
The problem is that you are deleting items from the array $t. You saved the count in $c, but the actual count will change by your last inner loop.
Even if you replace $c by count($t) everywhere, it will go wrong, because the last loop should be in reverse order, otherwise you skip items. For instance if you have the list 'a', 'b', 'c'. then when you delete 'b' and increment $r, you will not check 'c' at all.
So, if I fix those things, your code becomes as below. Although I didn't really check it for other issues. Frankly, I don't really get what is should do. ;-)
<?php
$p=fopen("g.txt","r");
$q=fread($p,filesize("g.txt"));
$t=explode(" ",$q);
$m=explode(" ",$q);
$i=0;
$j=0;
$r=0;
$count=0;
$d=array();
echo "count of"."<br/>";
for($i=0; $i<count($t); $i++)
{
for($j=$i; $j<count($t); $j++)
{
if($t[$i]==$t[$j])
{
$count=$count+1;
}
}
for($r=count($t) - 1; $r > $i; $r--)
{
if($t[$i]==$t[$r])
unset($t[$r]);
}
echo $t[$i]."=".$count."<br/>";
$count=0;
}
?>
In conclusion, you should do more tests. If the outcome of this script was okay, then it was by accident.
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've been learning PHP for a few days and I have an embarrassingly easy question. I want to sum the items in a 500 item loop. I want to figure out the total of 500 + 499 + 498, etc.
Here's my code:
for ($i=1; $i<=500; $i++)
{
// echo $i . "<br />";
$total = 0;
$total = $total + $i;
return $total;
}
echo $total . "<br />";
?>
Can't figure out what I'm doing wrong.
Pull out the initialization and the return statement from the loop:
$total = 0;
for ($i=1; $i<=500; $i++) {
echo $i . "";
$total = $total + $i;
}
echo $total . "";
return $total;
You can also do
echo array_sum(range(0,500)); // 125250
or do the entire calculation without a for body:
for( $total = $i = 0; $i <= 500; $total += $i++ );
echo $total; // 125250
and a couple of other approaches (Daniel's solution is particularly nice).
Both of the above are equivalent to what you are likely looking for
$total = 0;
for ($i=1; $i<=500; $i++) {
$total = $total + $i;
}
echo $total;
Like already pointed out elsewhere, when you do $total = 0; inside the for loop, you will overwrite the previous value for $total and putting return into it will end your script unless the loop is inside a function.
It looks like you simply need to move the $total = 0; line out of your loop... Otherwise it will be set to 0 on each iteration.
You also need to move that return $total; line outside, as #Webnet noted in a comment below.
Also note that you can do that calculation in constant time without iterating through all the numbers, by finding the sum of an arithmetic progression:
Sn = 1/2n(a1 + a2)
Sn = 250(1 + 500)
= 125250
Your code should be...
$total = 0;
for ($i=1; $i<=500; $i++) {
// echo $i . "<br />";
$total = $total + $i;
}
echo $total . "<br />";
return $total; will break the loop
Well, you're resetting $total to zero every time, and using return outside of a statement...
Anyways, the answer is (500*501)/2 = 250*501 = 125250 (basic maths)
You have two errors:
First, you set the $total to 0 each time the loop is repeated.
Then, you use return, what happens here is that it will cancel further execution, so the loop basically just was run once.
Try this.
$total = 0;
for ($i=1; $i<=500; $i++){
$total = $total + $i;
}
echo $total;
$total = 0;
for ($i=1; $i<=500; $i++) {
echo $i . "";
$total = $total + $i;
}
echo $total . "";
return $total;