php array interchange key value between two array
Get the solution ↓↓↓I have 2 array like
array (
0 => 'END PIECE',
1 => 'END PIECE',
2 => 'END PIECE',
3 => 'Title translation test 2',
4 => 'Title translation test 2',
5 => 'PIÈCE D\'EXTRÉMITÉ'
);
and
array (
0 => '47933',
1 => '47935',
2 => '47936',
3 => '47929',
4 => '47930',
5 => '47933'
);
I want to make ONE array from this 2 array like
array (
'END PIECE' => '47933',
'END PIECE' => '47935',
'END PIECE' => '47936',
'Title translation test' => '47929',
'Title translation test' => '47930',
'PIÈCE D\'EXTRÉMITÉ' => '47933'
);
Is it possible? PHP 5.3 version required, I have tried this
$c = array();
foreach($arr1 as $k => $val){
$c[] = array($arr2[$k] => $val);
}
But it not works
Answer
Solution:
There are two ways to do this, the simple version will always have a subarray...
$c = array();
foreach($arr1 as $k => $val){
$c[$arr2[$k]][] = $val;
}
print_r($c);
gives...
Array
(
[END PIECE] => Array
(
[0] => 47933
[1] => 47935
[2] => 47936
)
[Title translation test 2] => Array
(
[0] => 47929
[1] => 47930
)
[PIÈCE D'EXTRÉMITÉ] => Array
(
[0] => 47933
)
)
If you only want duplicates to have sub arrays, then you need to check when adding a new item if the item is already set and already an array, adjusting as you go along...
$c = array();
foreach($arr1 as $k => $val){
if ( isset ($c[$arr2[$k]])) {
if ( !is_array($c[$arr2[$k]]) )
$c[$arr2[$k]] = [$c[$arr2[$k]]];
$c[$arr2[$k]][] = $val;
}
else {
$c[$arr2[$k]] = $val;
}
}
print_r($c);
gives...
Array
(
[END PIECE] => Array
(
[0] => 47933
[1] => 47935
[2] => 47936
)
[Title translation test 2] => Array
(
[0] => 47929
[1] => 47930
)
[PIÈCE D'EXTRÉMITÉ] => 47933
)
As you can see, the PIÈCE D'EXTRÉMITÉ element is different in both cases.
Answer
Solution:
You can use array_combine() function it is working (PHP 5, PHP 7) like the following
$a = array('green', 'red', 'yellow');
$b = array('avocado', 'apple', 'banana');
$c = array_combine($a, $b);
print_r($c);
Output :
Array
(
[green] => avocado
[red] => apple
[yellow] => banana
)
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: uncaught error: call to undefined function mysqli_connect()
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.