0

I have a simple "if" code what works. In "array" it works but gets error "Undefined offset:". What is wrong?

code what works:

if (file_exists(glob($root . '/*/E0622.pdf')[0])) { 
    echo str_replace($root . '/', '', glob($root . '/*/E0622.pdf')[0]) ; 
} else {    
    echo 'x.pdf - no-no-no!' ;}

but in array gets " Parse error: syntax error, unexpected 'if' (T_IF) in ":

'E0622' => 'E0622' . if (file_exists(glob($root . '/*/E0622.pdf')[0])) { 
    echo str_replace($root . '/', '', glob($root . '/*/E0622.pdf')[0])   
} else {    
    echo 'x.pdf - no-no-no!' } ,

What will be wrong? Tnx!

jkddp
  • 1
  • 1

2 Answers2

4

The if statement itself cannot be used the way you are trying to do.

However, a short-hand if-else statement exists. It is introduced for cases like yours.

It looks like this: conditional-expression ? value-when-true : value-when-false. This is an expression, so you can insert it everywhere you would insert any other expression.

$var = 7;
echo ($var == 7 ? "Var is seven" : "Var is not seven");
// Those parentheses are optional, but I added them for clarity.

It echoes "Var is seven".

This works:

'E0622' => 'E0622' . (file_exists(glob($root . '/*/E0622.pdf')[0]) ? str_replace($root . '/', '', glob($root . '/*/E0622.pdf')[0]) : 'x.pdf - no-no-no!'),

PS: While you can nest as many short-hand if-else statements as you want, things may start to get really messy:

$a = 1 == 1 ? 2 == 2 ? 3 == 4 ? 9 : 8 == 8 ? 1 : 2 : 7 : 6;
MC Emperor
  • 22,334
  • 15
  • 80
  • 130
2

The if construct in PHP is not an expression, and cannot be used in concatenation.

You need to change your structure to setting a variable to the thing you want to concatenate first and then adding that variable to the string.

Erik
  • 3,598
  • 14
  • 29