0

I've set up a section on my site, to switch out content, based on the DIV ID called, but the initial "value" results in an error, if the variable isn't in the url.

the error i get:Undefined index: item

item is my variable.

My PHP is this:

<?php
    $url = 'file.php';
    $content = file_get_contents( $url );


    $item = $_GET[ 'item' ];
    switch ( $item ) {
        case "content1":
            $start = explode( '<div id="content1">', $content );
            $end = explode( "</div>", $start[ 1 ] );
            echo $end[ 0 ];
            break;

        case "content2":
            $start = explode( '<div id="content2">', $content );
            $end = explode( "</div>", $start[ 1 ] );
            echo $end[ 0 ];
            break;

        case "content3":
            $start = explode( '<div id="content3">', $content );
            $end = explode( "</div>", $start[ 1 ] );
            echo $end[ 0 ];
            break;

        default:
            $start = explode( '<div id="content1">', $content );
            $end = explode( "</div>", $start[ 1 ] );
            echo $end[ 0 ];
    }?>

So the code works fine if I append ?item=content1 at the end of my url, however, on initial visit (without the ?item= at the end) i get the above error ( Undefined index: item)

What can I do so that if someone visits say index.php I won't get the error, and throw up the default called content?

Keoki
  • 184
  • 4
  • 20

1 Answers1

1

Use an if statement to check if the variable is set. If not, set $item to a default value.

if (isset($_GET['item'])) {
    $item = $_GET['item'];
} else {
    $item = 'content1';
}

Also, there doesn't seem to be a need for the switch/case statement, since every case is identical except for what you're using as the explode delimiter.

$delimiter = '<div id="' . $item . '">';
$start = explode($delimiter, $content);
$end = explode("</div>", $start[ 1 ] );
echo $end[0];

It would probably be better to use DOMDocument and DOMXPath instead of string matching to parse your content.

You could also use the shorthand if statement for this if you want to get really fancy.

Chris Happy
  • 7,088
  • 2
  • 22
  • 49
Barmar
  • 741,623
  • 53
  • 500
  • 612