views:

55

answers:

3

Hi I'm about to type some 500 else if statements into my code (PHP) which have the exact same coding each:

if (color=White);
   rgb = 255-255-255;
   print rgb;
else if (color=Black);
   rgb = 0-0-0;
   print rgb;
else if (color=Red);
   rgb = 255-0-0;
   print rgb;
else if (color=Blue);
   rgb = 0-0-255;
   print rgb;
[the list keeps going]

I also (luckily) have a table that displays the color in the first column and rgb value in the next column for 500 of them... how do I use this to save time typing all those else if statements? Some how I have to reference the table file (made in excel, I'm guessing I'll have to save it as .csv?)

+1  A: 

Why aren't you printing rgb at the end of all the if-elses?

Frankly, your syntax is horrible, this is not valid PHP at all. Also, you should be using echo, not print.

if ($color=='White')
   $rgb = '255-255-255';
else if ($color=='Black')
   $rgb = '0-0-0';
else if ($color=='Red')
   $rgb = '255-0-0';
else if (color=='Blue')
   $rgb = '0-0-255';
[the list keeps going]
echo $rgb;

What I would do is store key-value pairs in an array like this:

$colors = array( 'white' => '255-255-255', 'black' => '0-0-0', 'blue' => '0-0-255' );

You can then access the RGB value from the array by providing the key, namely, the color string: $blueRGB = $colors[ 'blue' ];

Jacob Relkin
Thanks I value your reply, but it isn't just for PHP, I'm talking about conditional statements in general.
Haskella
+3  A: 

Your best bet is to put that data (color name to RGB value) into a database, then just do:

SELECT rgb FROM colors WHERE color = 'red';

If you can't do a database, you could use fgetcsv() and read CSV data into an array. Then just output:

echo $colors[$color];

To read a CSV file into an array, use something like:

//assuming the first field is color and the second rgb
$fh = fopen($file, 'r');
while (($row = fgetcsv($fh)) !== FALSE) {
  $colors[$row[0]] = $row[1];
}
Tim Lytle
Hrm, I see your point in database, but is there a clear advantage over CSV? I have absolutely no knowledge of MySQL. What about in terms of speed/bandwidth?Thanks this is the answer I'm looking for, hopefully it will work!
Haskella
The advantage is that with CSV you're turning PHP into the 'database' - loading all the data into memory every time a request is made. That's what databases are for, that's what databases are efficient at doing. Unless your dataset is small, it's faster (speaking of script execution time) to use a database to store the information.
Tim Lytle
A: 

You should use an array.

$colors = array(
    'white' => '255-255-255',
    'black' => '0-0-0',
    // etc.
);
echo $colors[$color];

If you have a CSV file, you could use fgetcsv.

$colors = array();
$handle = fopen('colors.csv', 'r');
while ($row = fgetcsv($handle, 10000))
    $colors[$row[0]] = $row[1];
echo $colors[$color];
Casey Hope
Thanks for the reply
Haskella