Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I use array values as keys?

I have an array named $stat that looks like this:

Array
(
    [0] => OK MPD 0.23.5
    [1] => repeat: 0
    [2] => random: 0
    [3] => single: 0
    [4] => consume: 1
    [5] => partition: default
    [6] => playlist: 11292
    [7] => playlistlength: 1
    [8] => mixrampdb: 0
    [9] => state: play
    [10] => song: 0
    [11] => songid: 3
    [12] => time: 14992:0
    [13] => elapsed: 14992.067
    [14] => bitrate: 48
    [15] => audio: 44100:16:2
    [16] => OK
)

I want to be able to use the array values (before the ":") as variables, instead of the numeric keys.

I need to do this, because the array keys returned change according to the player mode.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I have tried various methods, however I sense that my knowledge of PHP is simply not good enough to arrive at a solution.

The closest I have got is this:

foreach($stat as $list) {
        $list = trim($list);
//      echo "$list,";
        $list = "{$list}\n";
        $list = str_replace(": ", ",", $list);
        $xyz = explode(',', $list);
        $a=($xyz['0']);
        $b=($xyz['1']);
        echo "{$a}={$b}";
}

Which gives me this:

repeat=0
random=0
single=0
consume=1
partition=default
playlist=11642
playlistlength=1
mixrampdb=0
state=play
song=0
songid=3
time=15458:0
elapsed=15458.422
bitrate=50
audio=44100:16:2

If I try to create an array with the above output in the foreach loop, I end up with a multidimensional array which I can’t seem to do anything with.

Can anyone help please?

>Solution :

Not 100% sure if I understand what you want, but something like this perhaps:

// Init new empty array
$newStat = [];

foreach ($stat as $value) {
        $value = trim($value);
        // It is not really necessary to replace this, but I kept it as is
        $value = str_replace(": ", ",", $value);
        $split = explode(',', $value);
        $key = $split[0];
        $newValue = $split[1];

        // Add to empty array
        $newStat[$key] = $newValue;
}

echo $newStat['time']; // 15458:0

// You can also do
foreach ($newStat as $key => $value) {
    // Whatever you want
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading