0

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?

0

2 Answers 2

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.