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]);
}
Related
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;
Recently I am working with nest for loop but one loop work and another not working suppose I have 2 for loop.
For example
$data =DB::table('data')->get();
$job =DB::table('job')->get();
$recruiter =DB::table('recruiter')->get();
$admin =DB::table('commission')->get();
for($i=0;i<count($job);i++){
if(!$job->isEmpty()){
for($j=0;j<count($job);j++){
if( $data[$i]->job_id == $admin[$j]->job_id )
$job[$i]=$data[$i];
}
//if checking complete then skip $i or increment it (less than count($job)) or skip
//this index $i and continue with outer loop mean i++
}
}
I had done lots of research but haven't found any solution with this kind of problem
You have missed the $ in i and j
$data = DB::table('data')->get();
$job = DB::table('job')->get();
$recruiter = DB::table('recruiter')->get();
$admin = DB::table('commission')->get();
for($i=0; $i < count( $job ); $i++){
if($job->isEmpty()){
continue;
}
for($j=0; $j < count( $job ); $j++){
if( $data[$i]->job_id == $admin[$j]->job_id ){
$job[$i]=$data[$i];
}
}
}
I'm having a lot of trouble getting rid of this Undefined offset notice while using str_getcsv to read a CSV file and assign keys to it.
I've tried isset and array_key_exists which has been mentioned in other threads. isset did resolve undefined index notices but I can't remove the undefined offset notices:
$file = file("lookup.csv",FILE_SKIP_EMPTY_LINES);
$csv = array_map("str_getcsv",$file, array_fill(0, count($file), ';'));
$keys = array_shift($csv);
foreach ($csv as $i=>$row) {
$csv[$i] = array_combine($keys, $row);
}
$numberOfRows = count($csv);
$numberOfColumns = count(current($csv));
for ( $i = 0; $i <= $numberOfRows; $i ++ ) { // first loop to run thru to find correct sku template name in csv file
if ( $csv[$i]['sku'] === $sku ) { // if sku matches // Getting Undefined offset on this line
for ( $j = 0; $j <= $numberOfColumns; $j++) { // second loop to create variables from header line
${$keys[$j]} = isset($csv[$i][$keys[$j]]) ? $csv[$i][$keys[$j]] : ''; // // Getting 2 Undefined offset notices on this line
}
}
}
The CSV file in question does have some blank cells. Those blank cells will be maintained (I can't do anything about that).
Please can anyone point me in the right direction? Any help is much appreciated, thank you!
Try to remove the last element in the array, it sometimes is an empty item as an extra line in the file is picked up due to a new line character at the end of the actual last line.
$csv = array_map("str_getcsv",$file, array_fill(0, count($file), ';'));
array_pop($csv);
Ok, well I actually managed to figure it out myself.
The solution was to add isset - just in case it helps anyone else, here is my solution:
for ( $i = 0; $i <= $numberOfRows; $i ++ ) {
$csv[$i]['sku'] = isset($csv[$i]['sku']) ? $csv[$i]['sku'] : ''; // <-- isset added
if ( $csv[$i]['sku'] === $sku ) {
for ( $j = 0; $j <= $numberOfColumns; $j++) {
$keys[$j] = isset($keys[$j]) ? $keys[$j] : ''; // <-- isset added
$csv[$i][$keys[$j]] = isset($csv[$i][$keys[$j]]) ? $csv[$i][$keys[$j]] : '';
${$keys[$j]} = $csv[$i][$keys[$j]];
}
}
}
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 ) {
}
in general I think I understand what the error message means. But in my case, it's a riddle I didn't succeed in solving...
$keywords_all = array();
$count = 0;
for ($z = 0; $z < $num_results; $z++)
{
$keywords_array = explode(",", $row['free_keywords']);
for ($i = 0; $i < count($keywords_array); $i++)
{
if (in_array(strtolower(trim($keywords_array[$i])), $keywords_all))
{
$count++;
}
else
{
echo "<br />".$keywords_array[$i];
$keywords_all[$count] = $keywords_array[$i];
}
}
$row = pg_fetch_array($result);
}
So, what's wrong with that one? The error message pops up in the line
$keywords_all[$count] = $keywords_array[$i];
I have no clue, seems to be alright to me. But guess, it's again a tiny, tiny thing I've neglected... Thanks for any hints!
I was not able to reproduce your error message. I did find a bug in your code though (I am assuming that you are putting all your keywords in the $keywords_all array without any duplicates). So you should not increment $count inside your IF but instead update the $keywords_all count. See below:
if (in_array(strtolower(trim($keywords_array[$i])), $keywords_all)) {
$count = count($keywords_all);
} else {
echo "<br />".$keywords_array[$i];
$keywords_all[$count] = $keywords_array[$i];
$count++;
}
You will increment $count after storing a value to your $keywords_all array.
$keywords_all = array();
$count = 0; // what for you neet this var ?
$myRow = 'keyW1,keyW2,keyW3,keyW2';
// for ($z = 0; $z < $num_results; $z++) // there is no variable $num_results at your code so I've replaced it with constant
for ($z = 0; $z < 1; $z++)
{
// $keywords_array = explode(",", $row['free_keywords']);
$keywords_array = explode(",", $myRow);
// for ($i = 0; $i < count($keywords_array); $i++)
foreach ($keywords_array as $keyword)
{
$keyword = strtolower( trim( $keyword ) ); // some syntax sugar would be nice
if ( !in_array( $keyword, $keywords_all) )
{
echo "<br />".$keyword;
$keywords_all[] = $keyword;
}
}
// $row = pg_fetch_array($result);
}
var_dump($keywords_all);
This code would be better for you i think, but if you just want to get rid of duplicated records
array_uniq( array("1", "1", "2", "1") )
would be better solution for you.