-1

I have a simple Two array

    $ages[] = array("Peter"=>22, "Clark"=>32, "John"=>28);

    $ages1[] = array("demo"=>22);

When I print this arrays it should be like following:

Array
(
    [0] => Array
        (
            [Peter] => 22
            [Clark] => 32
            [John] => 28
        )

)
Array
(
    [0] => Array
        (
            [demo] => 22
        )

)

But I want to create third array which will be show demo kye value into first array like following:

Array
(
    [0] => Array
        (
            [Peter] => 22
            [Clark] => 32
            [John] => 28
            [demo] => 22
        )

)

Can we do two array into single array in PHP like Above

2
  • What have you tried? Show us your attempts, we will help debug them as required. Commented Oct 12, 2017 at 13:59
  • Duplicate: stackoverflow.com/questions/5394157/… Commented Oct 12, 2017 at 14:00

2 Answers 2

2

Not sure what are you trying to achieve here...little more context would be helpful. But this is how you can do this,

$ages[] = array("Peter"=>22, "Clark"=>32, "John"=>28);

$ages1[] = array("demo"=>22);

$result[] = array_merge($ages[0],$ages1[0]);
Sign up to request clarification or add additional context in comments.

Comments

0

This would do the job.

<?php    
$ages[] = array("Peter"=>22, "Clark"=>32, "John"=>28);
$ages1[] = array("demo"=>22);
$output = prepend_array($ages,$ages1);
print_r($output);

// Function to prepend arrays
function prepend_array()
{
    $num_args = count(func_get_args());
    $new_array = array();
    foreach (func_get_args() as $params){
        foreach($params as $out_key => $param)
        {
            foreach($param as $key => $value)
            $new_array[$out_key][$key] = $value;
        }
    }

    return $new_array;

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.