B. Godoak
B. Godoak

Reputation: 305

Create new array with key from array

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 ?

Upvotes: 0

Views: 63

Answers (3)

dhi_m
dhi_m

Reputation: 1265

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);
?>

Upvotes: 2

pr1nc3
pr1nc3

Reputation: 8338

<?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.

Upvotes: 1

MartinLeitgeb
MartinLeitgeb

Reputation: 63

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

Upvotes: 0

Related Questions