Jump to content

Remove blank values from array


everettcomstock

Recommended Posts

Hi, I am fairly new to PHP and I was wondering if someone could help me out with a script I am attempting to write. I am trying to read a file into an array. PHP makes that very easy with the file() function. However, the text file that I am reading has multiple lines that are completely blank. Is there a way to use fgets instead of file() to create an array that will not have blank entries? Or... is there a way to clean the array made by file so that all blank values are erased and all empty keys are deleted and re-numbered? Thanks for all of the help!

<?php

$file = file("playlist.txt");

print_r(array_values($file));


OR......


$filearray = array();

$y = "0";

$fp = "playlist.txt";

$file = fopen($fp,"r");

while (!feof($file)) {
$temp = fgets($file, 4096);
$trimtemp = trim($temp);
$filearray[$y] = $trimtemp;
$y++;
}

print_r(array_values($filearray));

?>
Link to comment
https://forums.phpfreaks.com/topic/27828-remove-blank-values-from-array/
Share on other sites

you could do this
[code]
$num=count($array)
while($count<$num)
{
if($array[$count]=="")
{
$array[$count]=$array[$count+1];
$array[$count+1]="";
}
$count++;
}

$count=0;
while($array[$count]!="")
{
$count++;
}
[/code]
this should sort the array and put the blank values at the end and then $count will have the highest array member.
You can also use array_diff(), with array_map(), so you trim() the file() array before trying to remove empty elements, because the only element in a file array that might be empty is the last element, because of EOL(s)!

[code]<?php

$my_file = './path/file.txt';

$file = array_diff ( array_map ( 'trim', file ( $my_file ) ), array ( '' ) );

?>[/code]


printf
Here's what seems to me to be the simplest solution..

[code=php:0]$filearray = array();
  while (!feof($file)) {
      $temp = fgets($file, 4096);
      $trimtemp = trim($temp);
      if (!empty($trimtemp)) $filearray[] = $trimtemp;
  }[/code]


There's no need to use $y to count if you are only adding to the end of an array.

Also, usually people would use $file for the filename and $fp for the file resource.  $fp is traditional to use as a return value from fopen(), since it's taken from C programming, where it would be a "file pointer".

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.