user1603264
user1603264

Reputation: 13

What is the best way to do this?

I don't want to repeat the same statements over and over again. What is the best way to do this?

<?php
if ($a = '3'){
  statement 1;
  statement 2;
  statement 3;
}else if ($a = '2'){
  statement 1;
  statement 2;
}else if ($a = '1'){
  statement 1;
}
?>

Upvotes: 1

Views: 91

Answers (2)

dani herrera
dani herrera

Reputation: 51705

To avoid repetitions, you can code:

<?php
 ($a == '3' or $a == '2' or $a == '1') and statement 1;
 ($a == '3' or $a == '2' ) and statement 2;
 ($a == '3' ) and statement 3;    
?>

Or, that is the same:

<?php
 if ($a == '3' or $a == '2' or $a == '1') { statement 1 ; }
 if ($a == '3' or $a == '2' ) {  statement 2; }
 if ($a == '3' ) {  statement 3; }   
?>

Also, take a look to Switch statement

Quoting php doc:

The following two examples are two different ways to write the same thing, one using a series of if and elseif statements, and the other using the switch statement:

<?php
if ($i == 0) {
    echo "i equals 0";
} elseif ($i == 1) {
    echo "i equals 1";
} elseif ($i == 2) {
    echo "i equals 2";
}

switch ($i) {
    case 0:
        echo "i equals 0";
        break;
    case 1:
        echo "i equals 1";
        break;
    case 2:
        echo "i equals 2";
        break;
}
?>

For your code:

<?php
switch ($a) {
        case '3':
          statement 1;
          statement 2;
          statement 3;
          break;
        case '2':
          statement 1;
          statement 2;
          break;
        case '3':
          statement 1;
          break;
}
?>

Upvotes: 3

ngen
ngen

Reputation: 8966

<?php

for ($i = 1; $i <= $a; $i++) {
 echo $statement . $i;
}

As danihp mentioned, you can use switch. Here's another way without breaks. The downfall of this approach is that you need to create a case for every possible value for $a.

<?php
switch ($a) {
        case '3':
          statement 3;
        case '2':
          statement 2;
        case '1':
          statement 1;
          break;
        default:
          break;
}

Upvotes: 1

Related Questions