phparrayslaravelnullunset

unset values null array multidimensional php


this is my first time on stackoverflow so sorry if I do something wrong. I would also appreciate your advice.

I have the next Array:

$dataPayment= [
  "operationType" => null
  "terminal" => 12345
  "payment" => array:14 [
    "terminal" => 12345
    "order" => "1234519997"
    "amount" => 100
    "currency" => "EUR"
    "secure" => 0
    "idUser" => 123456789"
    "tokenUser" => "zidkeKeu68Kld"
    "urlOk" => null
    "urlKo" => null
    "originalIp" => "1.130.151.28"
    "methodId" => 1
    "trxType" => "N"
    "userInteraction" => 1
    "scaException" => "MIT"
  ]
  "subscription" => array:2 [
    "startDate" => null
    "endDate" => null
  ]
]

And I want delete the null values. With array_filter also delete values 0, but I need those values 0. I tried with the following method:

private function arrayUnset( $dataPayment )
{
    foreach( $dataPayment as $key => $value ) 
    {
        if( is_array( $dataPayment[ $key ] ) )
        {
           $this->arrayUnset( $dataPayment[ $key ] );
        }
        if( $value === null || $value === "" ) 
        {
            unset( $dataPayment[ $key ] ); 
        } 
    }
    return $dataPayment;
}

But, only delete the first value.

$dataPayment = [
  "terminal" => 12345
  "payment" => array:14 [
    "terminal" => 12345
    "order" => "1234519997"
    "amount" => 100
    "currency" => "EUR"
    "secure" => 0
    "idUser" => 123456789"
    "tokenUser" => "zidkeKeu68Kld"
    "urlOk" => null
    "urlKo" => null
    "originalIp" => "1.130.151.28"
    "methodId" => 1
    "trxType" => "N"
    "userInteraction" => 1
    "scaException" => "MIT"
  ]
  "subscription" => array:2 [
    "startDate" => null
    "endDate" => null
  ]
]

And I would need the following array:

$dataPayment = [
      "terminal" => 12345
      "payment" => array:14 [
        "terminal" => 12345
        "order" => "1234519997"
        "amount" => 100
        "currency" => "EUR"
        "secure" => 0
        "idUser" => 123456789"
        "tokenUser" => "zidkeKeu68Kld"
        "originalIp" => "1.130.151.28"
        "methodId" => 1
        "trxType" => "N"
        "userInteraction" => 1
        "scaException" => "MIT"
      ]
    ]

Can you help me please?. Thanks.


Solution

  • You should passing argument by reference.

    private function arrayUnset( &$dataPayment )
    {
        foreach( $dataPayment as $key => $value ) 
        {
            if( is_array( $dataPayment[ $key ] ) )
            {
               $dataPayment[ $key ] = $this->arrayUnset($value);
            }
            if( $value === null || $value === "" ) 
            {
                unset( $dataPayment[ $key ] ); 
            } 
        }
        return $dataPayment;
    }