php - How can I map two arrays based on specific indexes?
Get the solution ↓↓↓Solution:
Code
Try the following:
<?php
$array1 = ["", "", "3", "", "5", "", ""];
$array2 = ["URD", "ISL"];
foreach($array1 as $id => $a1){
//for each item in array 1
if($a1){
//if the array 1 item has a value
$array1[$id] = array_shift($array2);
//replace it with an item from array 2
}
if(empty($array2)){
//if there are no more values left to share in array 2, stop
break;
}
}
var_dump($array1);
Output
array(7) {
[0]=>
string(0) ""
[1]=>
string(0) ""
[2]=>
string(3) "URD"
[3]=>
string(0) ""
[4]=>
string(3) "ISL"
[5]=>
string(0) ""
[6]=>
string(0) ""
}
Caveats
The method assumes that there will be values in both array 1 and array 2.
Once the values in array 2 have been split out and array 2 is empty, array 1 items with set values will no longer be affected.
The method does not care what the value set in array 1 is, just that there is a value.
Further reading
Codepen
Answer
Solution:
This solution works and simple to understands as OPS requested...
<?
$array1 = ["", "", "3", "", "5", "", ""];
$array2 = ["URD", "ISL"];
$i =0;
foreach($array1 as $keys=>$values) {
if($values == 3 || $values ==5) {
if(isset($array2[$i])){
$array1[$keys] = $array2[$i];
$i++;
}else { break; }
}
}
print_R($array1);
?>
it will replace the array2 values from array 1 values wherever 5 & 3 will come and which is independent of their sorting order. example
$array1 = ["5", "", "3", "", "", "", ""];
will be converted into
$array1 = ["URD", "" ,"ISL","","",""];
if you want it in order like 3 should always come first then first sort array1 then use my code... if you want 3 should be replace by URD and 5 should be replace by ISL then you if codition will be different
Answer
Solution:
Just another way to do it... (untested, but it should work)
<?php
$a = array ( 0 => '', 1 => '', 2 => 3, 3 => '', 4 => 5, 5 => '', 6 => '' );
$b = array ( 0 => 'URD', 1 => 'ISL' );
$c = array_replace ( $a, array_combine ( array_keys ( array_filter ( $a ) ), $b ) );
print_r ( $c );
?>
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: undefined array key php
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.
Similar questions
Find the answer in similar questions on our website.
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.