PHP fill array into for - php

in this below code i want to fill array with for repeator. echo can display and not have problem but. my array could not fill by for.
<meta charset='UTF-8' />
<?php
error_reporting(1);
$handle='A-file.txt';
$handle = file_get_contents($handle);
$lines = explode(PHP_EOL,$handle );
$names = array();
for( $i = 0; count($lines)-1 ; $i+=4 )
{
$names[]= $lines[$i];
//$names= $lines[$i];
//$names[]+= $lines[$i];
//echo $lines[$i];
}
print_r($names);
?>

You've forgotten the comparison with $i:
for( $i = 0; $i <= count($lines)-1 ; $i+=4 )
{
$names[]= $lines[$i];
//$names= $lines[$i];
//$names[]+= $lines[$i];
//echo $lines[$i];
}

Try this, You have missed to add $i < count($lines)-1
for( $i = 0; $i < count($lines)-1; $i+=4 )
instead of
for( $i = 0; count($lines)-1 ; $i+=4 )

Check the file has more than 4 lines, and the for finishes with that condition maybe will be an eternal loop.

This is perhaps just a tip to solve the problem more likely.
Use file() (http://php.net/file) to directly read a file's content into an array (so you don't need to do it manually with more lines then needed) and iterate over these lines using foreach($lines as $i => $line) {...} instead. To skip lines you can do:
if($i % $nthElem !== 0) continue;
You could even do it in one turn:
foreach(file($yourFile) as $i => $line){
if($i % 4 !== 0) continue;

Always optimize your for loop by putting count function out of for loop and store it in a variable. Use that in the loop
$count = count($lines);
for( $i = 0; $count-1 ; $i+=4 ) {
}

Related

Multiple comparisons inside for loops don't break php code. Why?

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.

loop error in php code

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;

for loop with if statement - array without comma

This is my part of code:
for( $i = $aKeys['iStart']; $i < $aKeys['iEnd']; $i++ )
{
$aData = $this->aProducts[$aProducts[$i]];
$content .= '"'.$aData['sName'].'"';
if ($i < $aKeys['iEnd'])
{
$content .= ', ';
}
$i2++;
}
Full code gives me this as result:
["word1", "word2", "word3", ]
This is a simple array, which I will use, but this won't work because after word3 there is a comma sign. How to write this if statement to get result like: ["word1", "word2", "word3"] ?
Put a condition on the length-1 to fix your bug.
for( $i = $aKeys['iStart']; $i < $aKeys['iEnd']; $i++ ){
$aData = $this->aProducts[$aProducts[$i]];
$content .= '"'.$aData['sName'].'"';
if ($i < $aKeys['iEnd']-1) {
$content .= ', ';
}
$i2++;
}
Alternatively you can use an array for this. And at the end simply implode them.
for( $i = $aKeys['iStart']; $i < $aKeys['iEnd']; $i++ ){
$aData = $this->aProducts[$aProducts[$i]];
$content[] = '"'.$aData['sName'].'"';
}
$content = '"' . implode('","', $content) . '"';
You can use rtrim() to remove comma.
rtrim($content, ',');
As I can see you want all names as comma separated. Than you can do like that as well :
$content = array();
for( $i = $aKeys['iStart']; $i < $aKeys['iEnd']; $i++ ){
$aData = $this->aProducts[$aProducts[$i]];
$content[] = $aData['sName'];
}
echo implode(',',$content);
for( $i = $aKeys['iStart']; $i < $aKeys['iEnd']; $i++ ){
$aData = $this->aProducts[$aProducts[$i]];
$content .= '"'.$aData['sName'].'"';
if ($i < $aKeys['iEnd'] && $i!=($aKeys['iEnd']-1)) { //this condition also considers $i not to be the last element of the array before appending the comma to it.
$content .= ', ';
}
$i2++;
}
Use array_push(); function
$var = array();
loop(condition){
array_push($var, $value);
}

loop php $_POST array names

I would like to loop 5 arrays in post.
What should be the right code to display:
$_POST["fp0"]
$_POST["fp1"]
..
$_POST["fp5"]
in a loop?
$x = 0;
while($x <= 5) {
$fp = ${'_POST["fp'.$x.'"]'};
echo $fp.'<br>';
$x++;
}
0 to 5 are six numbers, so you want to loop 6 elements in an array,
this is what you want
for( $i = 0; $i <= 5; $i++ ){
echo $_POST['fp'.$i]."<br>\n";
}
Try this:
$x = 0;
while($x <= 5) {
$fp = $_POST["fp$x"];
echo $fp.'<br>';
$x++;
}
You can do it simply by for loop, you form must POST values for
fp0, fp1 .... fp5
for($i = 0; $i < 5; $i++) {
$fp = $_POST['fp'.$i];
echo $fp . "<br>";
}

Error with php code, error displayed Undefined Offset

this line of code keeps getting me undefined offset: on line 9. I have no idea whats wrong with it, the codes runs smoothly but this part of the code is getting me undefined offset. i believe its something with $i
for( $i = 0; $lines[$i]; $i++ ) /** LINE 9 **/
{
if( $_POST['Aut'] == rtrim($lines[$i]) )
{
fwrite($file, $_POST['addition']."\n\t");
fwrite($file, $_POST['Aut'].PHP_EOL);
}
else
{
fwrite($fd,$lines[$i]);
}
for( $i = 0; $lines[$i]; $i++ )
When does the loop end? One iteration too late. It has to be
for( $i = 0; $i<count($lines); $i++ )
^
For Loop Syntax
for( $i = 0; **$lines[$i]**; $i++ )
Second step of for loop should be condition which is missing here
Try with -
foreach($lines as $line) /** LINE 9 **/
{
if( $_POST['Aut'] == rtrim($line) )
{
fwrite($file, $_POST['addition']."\n\t");
fwrite($file, $_POST['Aut'].PHP_EOL);
}
else
{
fwrite($fd,$line);
}
}
You should define the $lines array before using in the for loop.
$lines[] = array(1,2,3,4,5);
for( $i = 0; $lines[$i]; $i++ ) /** LINE 9 **/
{
print 'hai'; print PHP_EOL;
}
here, the "hai" would print 5 times from $lines[0] to $lines[4]. and the next it will return the same error, because there is no data on the $lines[5]
you can simply use the foreach for this purpose
foreach($lines as $key=>$line)
{
/* your code here */
}
if you want to do this with for loop try this one
for( $i = 0; $i<count($lines); $i++ ) /** LINE 9 **/
{
if( $_POST['Aut'] == rtrim($lines[$i]) )
{
fwrite($file, $_POST['addition']."\n\t");
fwrite($file, $_POST['Aut'].PHP_EOL);
}
else
{
fwrite($fd,$lines[$i]);
}

Categories