mafortis
mafortis

Reputation: 7138

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?

Upvotes: 0

Views: 400

Answers (2)

XMehdi01
XMehdi01

Reputation: 1

Use array_filter to filter out the array that return only if $name, $username are not null. Or even if one of them is null also not be returned.

$names = [0 => "qwfd",1 => "qw2e3",2 => "i am here",3 => null];
$usernames = [0 => "qwef",1 => "w2",2 => null,3 => null];

$newArray = array_combine($names, $usernames);
$newArray = array_filter($newArray,
              fn($name, $username)=>!is_null($name) and
                     !is_null($username),ARRAY_FILTER_USE_BOTH);

echo '<pre>'; print_r($newArray);

Prints:

Array
(
    [qwfd] => qwef
    [qw2e3] => w2
)

Upvotes: 0

nice_dev
nice_dev

Reputation: 17805

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);

Upvotes: 1

Related Questions