2

Please forgive the question as I'm not exactly sure of the terminology for this..

I am trying to create a grid of colour swatches and am using php foreach loop with associative array. I am trying to work out how I can set a variable for each colour and include this within the array as my code does not currently work

<?php
  $yellow = 'background: #FECD06';    
  $green = 'background: #069A48'; 
  $blue = 'background: #6BC9CB'; 
?>

<?php foreach ($colourSwatch as $swatch => $colour): ?>    

    <div class="colour">
        <div class="colour_box" style="background: <?php echo $colour[colour]; ?>"></div>
        <p><?php echo $colour[caption]; ?></p> 
    </div>

<?php endforeach ?>

Array

$colourSwatch = array(
colour1 => array(
    colour => $yellow,
    caption => "RAL 1023"
),

colour2 => array(
    colour => $green,
    caption => "RAL 2004"
),

colour3 => array(
    colour => $blue,
    caption => "RAL 3020"
)
)
glittergirl
  • 525
  • 3
  • 17

1 Answers1

1

There are a few mistakes you are making. First of all, in foreach ($colourSwatch as $swatch => $colour), when using ... => ..., these are always key and value pairs. Since you do not need to know the key, you can simply use foreach ($colourSwatch as $colour).

Secondly, In the array you are showing, there are no quotation marks (single or double) around the key-names, which also will not work.

Finally, if you want to access an item of an array like you are trying with $colour[colour], you must put the item in quotation marks as well, again single or double, so instead do $colour["colour"].

Here is your code with the corrections:

<?php

$yellow = '#FECD06';    
$green = '#069A48'; 
$blue = '#6BC9CB'; 

$colourSwatch = array(
 "colour1" => array(
    "colour" => $yellow,
    "caption" => "RAL 1023"
),

"colour2" => array(
    "colour" => $green,
    "caption" => "RAL 2004"
),

"colour3" => array(
    "colour" => $blue,
    "caption" => "RAL 3020"
));
?>

<?php foreach ($colourSwatch as $colour): ?>    

    <div class="colour">
        <div class="colour_box" style="background: <?php echo $colour['colour']; ?>">
        <p><?php echo $colour['caption']; ?></p> 
        </div>
    </div>

<?php endforeach ?>

Or see a live example.

Dirk J. Faber
  • 4,360
  • 5
  • 20
  • 58