Machete
Machete

Reputation: 11

Shorter code with For

Is there any way to make this code shorter ?

If ($Item_1 != "_") { $items1 = explode("_", $Item_1); } Else {}
If ($Item_2 != "_") { $items2 = explode("_", $Item_2); } Else {}
If ($Item_3 != "_") { $items3 = explode("_", $Item_3); } Else {}
If ($Item_4 != "_") { $items4 = explode("_", $Item_4); } Else {}
If ($Item_5 != "_") { $items5 = explode("_", $Item_5); } Else {}
If ($Item_6 != "_") { $items6 = explode("_", $Item_6); } Else {}
If ($Item_7 != "_") { $items7 = explode("_", $Item_7); } Else {}
If ($Item_8 != "_") { $items8 = explode("_", $Item_8); } Else {}
If ($Item_9 != "_") { $items9 = explode("_", $Item_9); } Else {}
If ($Item_10 != "_") { $items10 = explode("_", $Item_10); } Else {}
If ($Item_11 != "_") { $items11 = explode("_", $Item_11); } Else {}
If ($Item_12 != "_") { $items12 = explode("_", $Item_12); } Else {}

I try it make shorter with For but it doesnt work example:

  For ($i = 1; $i <= 12; $i++) {
    If (${$Item_ . $i} != "_") .... dont work for me :/
}

Any ideas?

Upvotes: 1

Views: 95

Answers (3)

hek2mgl
hek2mgl

Reputation: 157947

The idea is good. You just had a little error while building the variable name. Use the following code:

for ($i = 1; $i <= 12; $i++) {
    if (${"Item_$i"} != "_") .... should work 
}

What you are doing is called variable variables in php. Check the manual about that for further info and examples.


Another idea: Why not using an array? this should suite better here:

$item = array (
    'foo', 'bar', 'test', 'xyz', ...
);

for ($i = 1; $i <= count($item); $i++) {
    if ($item[$i] != "_") 
}

Further note, that you can use the ternary operator to shorten the if statement. (note that I wouldn't do that in this situation because it is less readable, but I'll at least mention it for completeness):

$item[$i] != "_" ? $other[$i] = 'something' : 1; // no else block, just a `NOP 1`;

Upvotes: 4

Jessica
Jessica

Reputation: 7005

You should probably be using arrays instead if var1, var2, etc. You could easily use a loop too.

Upvotes: 0

Sabeen Malik
Sabeen Malik

Reputation: 10880

For clarity try this:

$item_var = "Item_".$i;
If ($$item_var != "_"){}

Upvotes: 1

Related Questions