Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically populate an associative array in PHP

Tags:

arrays

php

I have an array with the following 6 strings.

user1 A
user2 B
user4 C
user2 D
user1 E

I need to create a Dictionary like:

arr['user1'] => ['A', 'E']
arr['user2'] => ['B', 'D']
arr['user4'] => ['C']

How to do this in PHP?

like image 686
blitzkriegz Avatar asked Oct 04 '12 06:10

blitzkriegz


1 Answers

This seems to work...

$arr = array();

foreach($lines as $line) {
    list($user, $letter) = explode(" ", $line);
    $arr[$user][] = $letter;
}

CodePad.

like image 106
alex Avatar answered Oct 01 '22 23:10

alex