array combine - How to fill a empty value in KEY=> VALUE for array_combine in php

32

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.

982

Answer

Solution:

You can do it viaforeach 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

625

Answer

Solution:

usearray_map() andarray_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

People are also looking for solutions to the problem: How to push array elemnt to specific position in another array using php

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.