John
John

Reputation: 393

Nesting if else statements in PHP to validate a URL

I'm currently writing up a function in order to validate a URL by exploding it into different parts and matching those parts with strings I've defined. This is the function I'm using so far:

function validTnet($tnet_url) {
    $tnet_2 = "defined2";
    $tnet_3 = "defined3";
    $tnet_5 = "defined5";
    $tnet_7 = "";

    if($exp_url[2] == $tnet_2) {
        #show true, proceed to next validation

        if($exp_url[3] == $tnet_3) {
        #true, and next

                if($exp_url[5] == $tnet_5) {
                #true, and last

                        if($exp_url[7] == $tnet_7) {
                        #true, valid
                        }
                }
            }
    } else {
        echo "failed on tnet_2";
    }
}

For some reason I'm unable to think of the way to code (or search for the proper term) of how to break out of the if statements that are nested.

What I would like to do check each part of the URL, starting with $tnet_2, and if it fails one of the checks ($tnet_2, $tnet_3, $tnet_5 or $tnet_7), output that it fails, and break out of the if statement. Is there an easy way to accomplish this using some of the code I have already?

Upvotes: 0

Views: 137

Answers (2)

air4x
air4x

Reputation: 5683

Combine all the if conditions

if(
   $exp_url[2] == $tnet_2 && 
   $exp_url[3] == $tnet_3 && 
   $exp_url[5] == $tnet_5 && 
   $exp_url[7] == $tnet_7
) {
  //true, valid
} else {
  echo "failed on tnet_2";
}

Upvotes: 1

xdazz
xdazz

Reputation: 160833

$is_valid = true;

foreach (array(2, 3, 5, 7) as $i) {
    if ($exp_url[$i] !== ${'tnet_'.$i}) {
        $is_valid = false;
        break;   
    }
}

You could do $tnet[$i] if you define those values in an array:

$tnet = array(
  2 => "defined2",
  3 => "defined3",
  5 => "defined5",
  7 => ""
);

Upvotes: 1

Related Questions