phparraysarray-combine

PHP array_combine if not null


I want to combine data only if value is exist. example:

// array 1
array:4 [▼
  0 => "qwfd"
  1 => "qw2e3"
  2 => null
  3 => null
]
// array 2
array:4 [▼
  0 => "qwef"
  1 => "w2"
  2 => null
  3 => null
]

I need to ignore 2=> and 3=> in both arrays as they are null.

Ps Even if one of them is null also needs to be ignored (example)

// array 1
array:4 [▼
  0 => "qwfd"
  1 => "qw2e3"
  2 => "i am here"
  3 => null
]
// array 2
array:4 [▼
  0 => "qwef"
  1 => "w2"
  2 => null
  3 => null
]

In this case array 1, 2=> has value but because array 2, 2=> doesn't. It shouldn't be combined either.

My code

$names = $request->input('social_media_name'); // array 1
$usernames = $request->input('social_media_username'); // array 2
$newArray = array_combine($names, $usernames);

Any idea?


Solution

  • It is pretty straightforward. Loop and check if values at indexes are null. If either of them are, skip it, else set the key and value pair.

    <?php 
    
    $result = [];
    
    foreach($names as $index => $val){
      if (is_null($val) || is_null($usernames[ $index ]) continue;
      $result[ $val ] = $usernames[ $index ];
    }
    
    print_r($result);