0

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?

2
  • I suggest you learn about PHP arrays and the for and foreach control structures. Commented Oct 6, 2012 at 3:34
  • there's a function parse_url() you can use this as well Commented Oct 6, 2012 at 3:40

2 Answers 2

1

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";
}
Sign up to request clarification or add additional context in comments.

1 Comment

I forgot all about if logic operators. Thank you!
1
$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 => ""
);

1 Comment

I'll definitely be checking out arrays and for loops, thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.