0

I want to transfer

Array
(
    [0] => name|smith
    [1] => kid|tom
    [2] => wife|emily
)

The fastest, smartest way into

Array
(
    [name] => smith
    [kid] => tom
    [wife] => emily
)

It's not a big deal to use foreach for that. But I would prefer a smart one-liner.

2
  • 3
    Just because you could do this in a one-liner, doesn't mean it's better or more readable than a foreach loop Commented Mar 16, 2016 at 11:07
  • You can use Regex for that. Commented Mar 16, 2016 at 11:13

3 Answers 3

1

try array_walk function:

$a = array
(
    0 => 'name|smith',
    1 => 'kid|tom',
    2 => 'wife|emily'
);

$new_arr = array();

array_walk($a, function($v, $k) use(&$new_arr){
    $arr = explode('|', $v);
    $new_arr[$arr[0]] = $arr[1];
});
print_r($new_arr);

output

Array
(
    [name] => smith
    [kid] => tom
    [wife] => emily
)
Sign up to request clarification or add additional context in comments.

1 Comment

YEAH! That did it. You are a smart sun of a gun. Thanks very VERY much. I am going to use this - unless someone comes up with a native php function which nobody has seen until now :-)
1

There are more than one ways to skin a cat.

Using array_reduce() (not in a single line, though):

$result = array_reduce(
    $a,
    function (array $carry, $item) {
        list($key, $value) = explode('|', $item);
        $carry[$key] = $value;
        return $carry;
    },
    array()
);

And a solution in a single line:

array_column(array_map(function($item) { return explode('|', $item); }, $a), 1, 0)

Please note that it requires PHP 5.5 (this is the version when the function array_column() was introduced).

1 Comment

A VERY smart way of handling it. Too bad I am using PHP 5.4.
0

Not a one-liner, but...

<?php

$a = array(
    'name|smith',
    'kid|tom',
    'wife|emily',
);

$a2 = array();

foreach($a AS $val) {
    list($key, $value) = explode("|", $val);
    $a2[$key] = $value;
}

print_r($a);
print_r($a2);

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.