0

I want to make a new array by specify key

For example I have an array:

$data = [
    0 => 'name',
    1 => '29',
    2 => '7/26 City Avenue',
]

And I want to make new array like this

$data = [
    'name' => 'name',
    'age' => '29',
    'address' => '7/26 City Avenue',
]

How to make new array like above example ?

3
  • 2
    Have a look on array_combine and array_values. Commented Nov 24, 2017 at 10:42
  • Easy if thats all, but im suspecting its not 3v4l.org/K7DpW Commented Nov 24, 2017 at 10:45
  • 1
    @SahilGulati Ahh array_combine is what i need. Thanks Commented Nov 24, 2017 at 11:32

3 Answers 3

2

Please try this

<?php
$keylabel=array("name","age","address");
$data=array("name","29","7/26 City Avenue");
$data_keylabel=array_combine($keylabel,$data);
print_r($data_keylabel);
?>
Sign up to request clarification or add additional context in comments.

1 Comment

You just save my life haha. Thanks
1
<?php


$data = [
    0 => 'name',
    1 => '29',
    2 => '7/26 City Avenue',
];

$data['name'] = $data[0];
unset($data[0]);
$data['age'] = $data[1];
unset($data[1]);
$data['address'] = $data[2];
unset($data[2]);

print_r($data);

This is an example. Your new array has the keys set in the way you want.

2 Comments

I can't use unset for my case but, anyway. Thanks.
Then just create a new array and pass the data there.
0

The simplest but NOT cleanesr solution would be parsing it into a new array like

$data_new = [];
$data_new['name'] = $data[0];
$data_new['age' = $data[1];
$data_new['address'] = $data[2];

Cleaner would be array_combine

Example from the reference Link

$a = array('gruen', 'rot', 'gelb');
$b = array('avokado', 'apfel', 'banane');
$c = array_combine($a, $b);

Output:
Array ( [gruen] => avokado [rot] => apfel [gelb] => banane )

Hope that helps

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.