1

Given these two array:

$name=array("alice","ken","wendy");

$frequent=array(3,6,9);                                       

I try to combine it like

$data = array($name=>$frequent);

but it fails. Anyone can help?

I want this:

$data = array(
      'alice' => 3,
      'ken' => 6,
      'wendy' => 9,
 );
3
  • And whats your expected output Commented Jun 4, 2015 at 6:43
  • What is your expected outcome? Commented Jun 4, 2015 at 6:46
  • I want to take out the data from database and store in different array so that i can plot a graph for it. But there is a problem occur when i take out the data. I just take out part of the coding. $namelist=array($name); $no=array($count); $data = array_combine($namelist, $no); print_r ($data); the output i get is only 1 data as there should be 2 data inside the database. How can I solve it? Commented Jun 4, 2015 at 7:31

5 Answers 5

4

You can use array_combine

$combined_array = array_combine($name, $frequent);

Documentation here: http://php.net/manual/en/function.array-combine.php

Sign up to request clarification or add additional context in comments.

Comments

4

You can use array_combine function as

Syntax:

array_combine ( array $keys , array $values )

So yours is like

$name=array("alice","ken","wendy"); 
$frequent=array(3,6,9);
$result = array_combine($name,$frequent);

Output

Array
(
    [alice] => 3
    [ken] => 6
    [wendy] => 9
)

Comments

2
[akshay@localhost tmp]$ cat test.php
<?php

$name=array("alice","ken","wendy");
$frequent=array(3,6,9);

// One easy way is
print_r(  array_combine($name, $frequent) );


// Another lengthy way
while ( ($key = array_shift($name)) && ($value = array_shift($frequent)) )
{
    $combined[$key] = $value;
}

print_r( $combined );

?>

Output

[akshay@localhost tmp]$ php test.php
Array
(
    [alice] => 3
    [ken] => 6
    [wendy] => 9
)
Array
(
    [alice] => 3
    [ken] => 6
    [wendy] => 9
)

Comments

2

write like this $combined_array = array_combine($name, $frequent);

1 Comment

Write descriptive answers as written by other users. And use correct formatting.
1

If you want to do it manually.

<?php
    $name=array("alice","ken","wendy");
    $frequent=array(3,6,9);
    $combined=array();
    for($i=0; $i<3; $i++)
    {
        $combined[$name[$i]]=$frequent[$i];
    }
    var_dump($combined);
?>

1 Comment

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.