Jump to content

Recommended Posts

Beginner here:

 

I have a array with numbers out of a database, and they correspond with words.

 

This is the translation I already know:

1 = bread

2 = pizza

3 = water

ect...

 

Lets's say the array contains the following numbers:

 

$aWords = array (1, 2, 4, 5, 7, 12, 15);

 

Now I want to check if a number is in the array, and then echo a image if it is there, so a bread image for 1, and a pizza image for 2. I used a switch, but this stopped after finding the first case. I can use a lot of if statements but is there not a easier function I can use?

 

I have build this array, but I have really no clue how to finish the coding.

 

$aTranslate = array(

    1  => 'bread',

    2 => 'piza',

    3 => 'water',

4 => 'cornflakes',

5 => 'word5',

6 => 'word6',

7 => 'word7',

8 => 'word8',

9 => 'word9',

 

);

 

What does:

 

foreach($aWords as $key => $value)

 

the relation $aWords as $key => $value mean?

 

If I echo $aTranslate in the foreach I get "array" repeated every time. If I change $key to $aTranslate:  foreach($aWords as $aTranslate => $value)

 

Then it counts from 0 to 5 if I use 6 values in $aWords = array(1, 2, 5, 7, 8, 9);

$aWords = array(1, 2, 4, 5, 7, 12, 15);

$aTranslate = array(
    1 => 'bread',
    2 => 'piza',
    3 => 'water',
    4 => 'cornflakes',
    5 => 'word5',
    6 => 'word6',
    7 => 'word7',
    8 => 'word8',
    9 => 'word9',  
);

foreach($aWords as $key => $value) {
  $alt = '';
  if (isset($aTranslate[$key])) {
    $alt = $aTranslate[$key];
  }
  echo '<img src="http://example.com/imagepath/' . $value . '.jpg" alt="' . $alt . '"><br>';
}

Hi  ignace, thanks for your help,

 

I have tested your code, but it doesn't work the right way. It translates the keys of the first array, i.e: array(1, 2, 4, 5, 7, 12, 15);

 

into the words list

 

  1 => 'bread',

    2 => 'piza',

    3 => 'water',

    4 => 'cornflakes',

    5 => 'word5',

    6 => 'word6',

    7 => 'word7',

    8 => 'word8',

    9 => 'word9', 

 

So the first one is empty, because the key is 0, and then it translates the keys from bread until word6, not the real translation.

 

Any solution?

 

 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.