0

I wish to make Key and Value combining with 2 arrays, but both arrays are not equal.

$array1 = array("1","2","3","4","5");
$array2 = array("apple","banana","","dog","");
$key_value = array_combine($array1,$array2);

The output is:

array_combine(): Both parameters should have an equal number of elements

But I need to below output be like

print_r($key_value);
array(5) { 
          [1]=> string(5) "apple" 
          [2]=> string(6) "banana" 
          [3]=> string(8) "No Value" 
          [4]=> string(3) "dog" 
          [5]=> string(8) "No Value" 
         }

How can do this if null, insert "no value" text.

2 Answers 2

1

You can do it via foreach loop:

$res = [];
foreach($array1 as $ind=>$num){
    $res[$num] = $array2[$ind] === "" ? "No Value" : $array2[$ind]; 
}

print_r($res);

Output:

Array
(
    [1] => apple
    [2] => banana
    [3] => No Value
    [4] => dog
    [5] => No Value
)

Demo

Sign up to request clarification or add additional context in comments.

Comments

0

use array_map() and array_combine()

<?php

$array1 = array("1","2","3","4","5");
$array2 = array("apple","banana","","dog","");

 $array2 = array_map(function($v){
        return (empty($v)) ? "No Value" : $v;
    },$array2);

$key_value = array_combine($array1,$array2);
print_r($key_value);

https://3v4l.org/CY4ku

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.