1

Here's a very simplified example of what I am trying to achieve :

GIFT
sender  |  type
phil    |  1
phil    |  2

Here, 1 = cake and 2 = muffin.

$table = query("SELECT sender, type FROM users WHERE sender = Phil");
foreach ($table as $row) {
$sender = $row['sender'];
$type = $row['type'];

echo '$sender has bought a $type';
}

This will output :

Phil has bought a 1
Phil has bought a 2 

How can I get the below output instead ?

Phil has bought a cake
Phil has bought a muffin

Should I use an array ?

 $type = array(
 1 => 'cake',
 2 => 'muffin'
 );

The problem is $type is already defined as $row['type'].

3 Answers 3

1

Use an associative array that relates numbers to names:

$types = array(1 => 'cake', 2 => 'muffin');

Then use it as:

echo "$sender has bought a {$types[$type]}";

Note that you must use doublequotes for variables to be expanded inside the string, not singlequotes as in your code.

Sign up to request clarification or add additional context in comments.

Comments

1

Or if you'd like to return this from database:

$table = query("SELECT sender, 
                case when type = '1' then 'cake' 
                     when type = '2' then 'muffin'
                end as type 
                FROM users WHERE sender = Phil");

foreach ($table as $row) {
  $sender = $row['sender'];
  $type = $row['type'];

  echo "$sender has bought a $type"; //Use double quotes for $sender and $type to be interpolated.
}

Comments

0

Given your example, I would use an array like this:

$items = array(
    "1" => "cake",
    "2" => "muffin"
);

Then do this:

echo "$sender has bought a {$items[$type]}";

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.