Search code examples
phparraysassociative-arrayphp-5.4

How to remove all null values inside an array, which is enclosed within an associate array, in PHP?


My question may seem fairly simple, but I have tried multiple techniques, and none seem to yield a proper answer.

I have an associative array as follows:

$array = array("TB1_course" => array(null, 'CHEM 2E03', null, "BIO 1A03"),  
          "TB1_section" => array(null, 'CHEM 2E03', null, "BIO 1A03"), 
          "TB1_session" => array(null, 'CHEM 2E03', null, "BIO 1A03")
          );

Now I would like to remove all the null elements in my arrays, for the respective associative array.

My attempt was as follows:

foreach($array as $key=>$value){
    for($i=0; $i<sizeof($value);$i++){
        if ($value[$i]==null){
           unset($value[$i]); 
        }
        $array[$key]=$value;
    }
}

print_r($array);

But my output is also retianing the indexes of the array. My output is as follows:

Array
(
[TB1_course] => Array
    (
        [1] => CHEM 2E03
        [3] => BIO 1A03
    )

[TB1_section] => Array
    (
        [1] => CHEM 2E03
        [3] => BIO 1A03
    )

[TB1_session] => Array
    (
        [1] => CHEM 2E03
        [3] => BIO 1A03
    )

)

I would like to remove the indexes, so that there are only two elements inside of my arrays. "CHEM 2E03" should be the 0th index, and "BIO 1A03" should be the 1st index. I am using PHP 5.4.


Solution

  • The array_values() function retains the value and resets the indexed of the array. Below is it's implementation for your purpose:

    foreach($array as $key=>$value){
      for($i=0; $i<sizeof($value);$i++){
        if ($value[$i]==null){
           unset($value[$i]); 
        }
        $array[$key] = array_values($value);
      }
    }