0

I'm trying to make a script to remove any empty elements from my array.

However an empty element is in the [0] slot so when I unset the value it deletes my whole array. At least I think that's what's happening, why isn't this working?

<?php

$idfile = file_get_contents("datafile.dat");
$idArray = explode("\n", $idfile);
print_r($idArray);
foreach ($idArray as $key => &$value) {
    echo "Key is: ".$key." and value is: ".$value."<br />\n";
    if ($value == ""){
        echo "Killing value of ".$value."<br />";
        unset($value[$key]);
    }
    $value = str_replace("\n", "", $value);
    $value = str_replace("\r", "", $value);
    $value = $value.".dat";
}

print_r($idArray);
?>

Here's the output:

Array
(
    [0] => 
    [1] => test1
    [2] => test2
)
Key is: 0 and value is: <br>
Killing value of <br>
Tim Withers
  • 12,072
  • 5
  • 43
  • 67

2 Answers2

4

If you are just removing an empty value try using unset($idArray[$key]) instead. If you are just trying to remove the first element overall, use array_shift()

Tim Withers
  • 12,072
  • 5
  • 43
  • 67
1

Another nice solution would be to use the array_filter() method, which will handle the iteration and return the filtered array for you:

<?php

function isNotEmpty($str)
{
    return strlen($str);
}

$idfile = file_get_contents("datafile.dat");
$idArray = explode("\n", $idfile);
$idArray = array_filter($idArray, "isNotEmpty");

?>
Alex Kalicki
  • 1,533
  • 9
  • 20