Search code examples
phparraysunset

PHP Remove empty value from array with unset not working correctly


I have a string containing sentences. I wish to break these sentences into an array, then modify each array item, including removing any array items that are empty.

Here's what I have:

//Explode string by dot
$items_array = explode(".", $raw_data);

//Loop through the array
foreach ($items_array as $i => $item) {

  //Remove any whitespace at front of item
  $item= ltrim($item);

  //Check if array item is empty and unset
  if($item === NULL){
    unset($items_array[$i]); 
  }

  //Reinstate the dot
  $item .= '.';
}

However, this does not work. I see extra '.' and if I put a print(strlen($item)); within the loop (after the unset) I see a few 0 results.

I know the if condition is being met because if I put a print in there it will trigger the same amount of times a 0 appears, eg:

 if($item === NULL){
      print("no value");
      unset($raw_inclusions[$i]); 
    }

Have I done something wrong here?

Example $raw_data string. Assume I have no control over what is placed here.

$raw_data = "Brown fox. Lazy dog."

Expected/desired result:

$items_array = array("Brown fox.", "Lazy dog.");

Current result:

$items_array = array("Brown fox.", "Lazy dog.", ".");

Solution

  • It's actually pretty easy, you are just missing 1 line of code

    Your Code

    if($item === NULL){
        unset($items_array[$i]); 
    }
    //Reinstate the dot
    $item .= '.';
    

    Make it this

    if($item === NULL){
        unset($items_array[$i]); 
    }
    else // <- The else is important
    //Reinstate the dot
       $item .= '.';
    

    And you need this line

    $items_array[$i] = $item;
    

    for anything to work (including your original code)