Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split array to create an associative array

Tags:

arrays

php

I have an array that looks like this:

a 12 34
b 12345
c 123456

So the array looks like

$array[0] = "a 12 34"
$array[1] = "b 12345"
$array[2] = "c 123456"

I am trying to create an associative array such that

[a] => 12 34
[b] => 12345
[c] => 123456

Can I possibly split the array into two, one for containing "a, b, c" and another for their contents and use the array_combine()? Or are there any other ways?

like image 863
angielle Avatar asked Aug 30 '26 20:08

angielle


1 Answers

You can do that within a loop like the snippet below demonstrates. Quick-Test here:

        $array      = array("a 12 34", "b 12345", "c 123456");
        $array2     = array();

        foreach($array  as $data){
            preg_match("#([a-z])(\s)(.*)#i", $data, $matches);
            list(, $key, $space, $value)    = $matches;
            $array2[$key]   = $value;
        }

        var_dump($array2);
        // YIELDS::
        array(3) {
            ["a"]=>  string(5) "12 34"
            ["b"]=>  string(5) "12345"
            ["c"]=>  string(6) "123456"
        }

Or using a Blend of array_walk() and array_combine() which can be Quick-Tested Here.

        <?php

            $array      = array("a 12 34", "b 12345", "c 123456");
            $keys       = array();

            array_walk($array, function(&$data, $key) use (&$keys){
                $keys[] = trim(preg_replace('#(\s.*)#i',   '', $data));;
                $data   = trim(preg_replace('#(^[a-z])#i', '', $data));
            });

            $array = array_combine($keys, $array);

            var_dump($array);;
            // YIELDS::
            array(3) {
                ["a"]=>  string(5) "12 34"
                ["b"]=>  string(5) "12345"
                ["c"]=>  string(6) "123456"
            }
like image 63
Poiz Avatar answered Sep 02 '26 09:09

Poiz