Q:

Write a PHP script to combine (using one array for keys and another for its values) the following two arrays

0

Write a PHP script to combine (using one array for keys and another for its values) the following two arrays.

('x', 'y', 'y'), (10, 20, 30)

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

<?php
function combine_Array($keys, $values)
{
    $result = array();
    foreach ($keys as $i => $k) {
        $result[$k][] = $values[$i];
    }
    array_walk($result, create_function('$v', '$v = (count($v) == 1)? array_pop($v): $v;'));
    return    $result;
}
$array1 = array('x', 'y', 'y');
$array2 = array(10, 20, 30);
print_r(combine_Array($array1, $array2));
?>

Sample Output:

Array                                                       
(                                                           
    [x] => Array                                            
        (                                                   
            [0] => 10                                       
        )                                                   
                                                            
    [y] => Array                                            
        (                                                   
            [0] => 20                                       
            [1] => 30                                       
        )                                                   
                                                            
)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now