Jump to content

[SOLVED] IF ELSE IF ELSE


fesan

Recommended Posts

Hello....

 

I'm making a page that lists out data from my database. It is working that's not the issue but as i was programming i thought that it must be an easier way to do this.

 

First page is some links:

<a href="index.php?page=list_produkter&produkt_id=mac_600" />
<a href="index.php?page=list_produkter&produkt_id=mac_300" />

and so on....

 

At the page "list_produkter" I want to add some different codes for the different "produkt_id". I solved this by doing the following:

<?php
$produkt_id = $_GET[produkt_id];
if($produkt_id=="mac_250") {
echo "250 Liste";
} else {
if($produkt_id=="mac_300") {
echo "300 Liste";
} else {
if($produkt_id=="mac_600") {
echo "600 Liste";
}}} ?>

 

Is there a more clever way to do this?

Link to comment
https://forums.phpfreaks.com/topic/140576-solved-if-else-if-else/
Share on other sites

you can use the if else like this

 

if($produkt_id=="mac_250") {
echo "250 Liste";
} elseif($produkt_id=="mac_300") {
echo "300 Liste";
} elseif($produkt_id=="mac_600") {
echo "600 Liste";
}

you could use a switch

switch($produkt_id){
    case "mac_250":
        echo "250 Liste";
        break;
    case "mac_300":
        echo "300 Liste";
        break;
    case "mac_600":
        echo "600 Liste";
        break;
}

or if you just want the number

echo substr($produkt_id,4) . " Liste";

 

Scott.

switch might look better, as long as you keep it simple. For long lists of items, a lookup table will be better.

 

$lookupNames = array(
  "mac_250" => "250 Liste",
  "mac_300" => "300 Liste",
  "mac_600" => "600 Liste",
);

$produkt_id = $_GET[produkt_id];

echo $lookupNames[$produkt_id];

 

 

Thank you guys....

Think the perfect solution for me is the switch(). That i didn't think of that myself...  :-[

The thing is that I'm gonna write out a lot of HTML between the cases, so by my judgement the switch is a easy way to have controll of the "big" script.

 

Unless there is some kind of "goto" function.  :)

 

Thanks again!

As mchl said. Having 30 row's in a switch function can/could get messy. When you can rather have a much easier url such as:

 

<a href="index.php?page=list_produkter&produkt_id=600&n=mac">

 

Then of course in the php page:

 

<?php

$produkt_id = abs(@intval($_GET['produkt_id']));

$name        = $_GET['n'];

echo $produkt_id.' Liste '.$name;

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.