Arnold Porche Villaluz
Arnold Porche Villaluz

Reputation: 213

PHP IF condition?

How would I better write an IF statement for this condition?

I have 4 variables to check wheather it's null or not.

$pdf_locator21e, $pdf_locator21d, $pdf_locator21c, $pdf_locator21b

  1. IF $pdf_locator21e has values { $pdf_original = "forms\pdfForms\5pg.pdf"; } IF it's NULL, then move to step 2

  2. IF $pdf_locator21d has values { $pdf_original = "forms\pdfForms\4pg.pdf"; } IF it's NULL, then move to step 3

  3. IF $pdf_locator21c has values { $pdf_original = "forms\pdfForms\3pg.pdf"; } IF it's NULL, then move to step 4

  4. IF $pdf_locator21b has values { $pdf_original = "forms\pdfForms\2pg.pdf"; } IF it's NULL

ELSE

{ $pdf_original = "forms\pdfForms\CMS-485-487-1pg.pdf"; }

I want to check is IF $pdf_locator21e has values first, then it will use 5pg.pdf and STOP checking for pdf_locator21d, pdf_locator21c, and pdf_locator21b.

IF pdf_locator21e is NULL then it will check for pdf_locator21d, and so on..

Upvotes: 0

Views: 596

Answers (3)

Francois Deschenes
Francois Deschenes

Reputation: 24969

You want to use if, elseif, and else. Additionally the empty function allows you to check is a variable is not empty (or not null). In the example below I'm using the ! to do the opposite (i.e. if not empty). The reason I choose to use that instead of just if($prd_locator21e) is because if it's not set, that would result in PHP Warning: error messages because the variable isn't set.

You're looking for something along these lines:

if ( ! empty($pdf_locator21e) )
  $pdf_original = "forms\pdfForms\5pg.pdf";
elseif ( ! empty($pdf_locator21d) )
  $pdf_original = "forms\pdfForms\4pg.pdf";
elseif ( ! empty($pdf_locator21c) )
  $pdf_original = "forms\pdfForms\3pg.pdf";
elseif ( ! empty($pdf_locator21b) )
  $pdf_original = "forms\pdfForms\2pg.pdf";
else
  $pdf_original = "forms\pdfForms\CMS-485-487-1pg.pdf"

As pointed in the comments below, you could use isset instead of ! empty to check if a variable is set. The difference is that it would allow values like FALSE or 0 or an empty string which are considered to be empty.

For example:

if ( isset($pdf_locator21e) )
  $pdf_original = "forms\pdfForms\5pg.pdf";

Upvotes: 2

Chandresh M
Chandresh M

Reputation: 3828

you can use isset() function for your task.

    if (isset($pdf_locator21e) && $pdf_locator21e != "")
      $pdf_original = "forms\pdfForms\5pg.pdf";
    else
      $pdf_original = "forms\pdfForms\CMS-485-487-1pg.pdf"

and so on....

Thanks.

Upvotes: 0

Nanne
Nanne

Reputation: 64399

I'd say you use if ... elseif....else

so

if($pdf_locator21e){
      $pdf_original = "forms\pdfForms\5pg.pdf";
}elseif($pdf_locator21d){
       pdf_original = "forms\pdfForms\4pg.pdf"; 
...
}else{
    $pdf_original = "forms\pdfForms\CMS-485-487-1pg.pdf"; 
}

Upvotes: 0

Related Questions