I have already the values from another array, my problem is how can I show the duplicate values in an array?
I have tried this using array_intersect_key and don't know how to show duplicates and assign their values.
$name = "ALLISON";
function toNumber($name) {
$nameArr = str_split($name);
$convertArr = array(
'A'=>'1', 'J'=>'1', 'S'=>'1',
'B'=>'2', 'K'=>'2', 'T'=>'2',
'C'=>'3', 'L'=>'3', 'U'=>'3',
'D'=>'4', 'M'=>'4', 'V'=>'4',
'E'=>'5', 'N'=>'5', 'W'=>'5',
'F'=>'6', 'O'=>'6', 'X'=>'6',
'G'=>'7', 'P'=>'7', 'Y'=>'7',
'H'=>'8', 'Q'=>'8', 'Z'=>'8',
'I'=>'9', 'R'=>'9'
);
$result = array_intersect_key($convertArr, array_flip($nameArr));
foreach($convertArr as $key => $val) {
if(array_search($key, $nameArr) === false) {
unset($convertArr[$key]);
}
}
print_r($result);
}
echo toNumber($name);
The output I got is this:
Array ( [A] => 1 [S] => 1 [L] => 3 [N] => 5 [O] => 6 [I] => 9 )
And this is the output I want:
Array ( [A] => 1 [S] => 1 [L] => 3 [L] => 3 [N] => 5 [O] => 6 [I] => 9 )
CodePudding user response:
You cannot create an array with twice the same key, in your case 'L'. What you can do is this:
$name = 'ALLISON';
function toNumber($name) {
$nameArr = str_split($name);
$convertArr = array(
'A'=>'1', 'J'=>'1', 'S'=>'1',
'B'=>'2', 'K'=>'2', 'T'=>'2',
'C'=>'3', 'L'=>'3', 'U'=>'3',
'D'=>'4', 'M'=>'4', 'V'=>'4',
'E'=>'5', 'N'=>'5', 'W'=>'5',
'F'=>'6', 'O'=>'6', 'X'=>'6',
'G'=>'7', 'P'=>'7', 'Y'=>'7',
'H'=>'8', 'Q'=>'8', 'Z'=>'8',
'I'=>'9', 'R'=>'9'
);
return array_reduce($nameArr, function ($carry, $item) use ($convertArr) {
return [ ...$carry, [$item => $convertArr[$item]] ];
}, []);
}
print_r(toNumber($name));
It will create an array of arrays:
Array
(
[0] => Array
(
[A] => 1
)
[1] => Array
(
[L] => 3
)
[2] => Array
(
[L] => 3
)
[3] => Array
(
[I] => 9
)
[4] => Array
(
[S] => 1
)
[5] => Array
(
[O] => 6
)
[6] => Array
(
[N] => 5
)
)