Using Key:Value pairs in PHP arrays

J was working on the exercise to display personalised greetings and wondered if there was a better way than lots of:

if($user == "J") {
echo ("J, you're awesome");

One method is to create an array of users with their personal message and then use the username as the key to extract their personal message.

Here’s an example:

// create the array
$messages = array (
"Charlie" => "Hello Charlie" ,
"Jordan" => "Watcha Mate" ,
"Nathan" => "Hiya Nathan"

// decide who the person is
$person = "Jordan";

// write the message
echo ("

A personal message for " . $person . ": " . $messages["Jordan"]);

There’s a full example on GitHub:

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s