SLIM Optional

I am trying to achieve something similar in Slim PHP:

page / p1 / p2 / p3 / p4

I want that if I leave the parameters to the right (obviously), then I want to do my things based on any parameters that I received.

$app->get('/page(/)(:p1/?)(:p2/?)(:p3/?)(:p4/?)', function ($p1 = null, $p2 = null, $p3 = null, $p4 = null) { print empty($p1)? : '' . "p1: $p1/<br/>"; print empty($p2)? : '' . "p2: $p2/<br/>"; print empty($p3)? : '' . "p3: $p3/<br/>"; print empty($p4)? : '' . "id: $p4<br/>"; }); 

Everything works as expected, but the problem occurs when I delete a parameter from the end, it prints 1 for each parameter that I delete. why is that so? what am i doing wrong here?

0
source share
1 answer

Since you omitted the second part of the triple (which should print if the test operator returns true ), the three-dimensional operator returns the result that the test expression evaluates to. Then this result is printed.

When you omit the last parameter on the route, the test expression is displayed in true , but since you do not determine what to do in this case, true returned and 1 printed.

Try this instead:

 $app->get('/page(/)(:p1/?)(:p2/?)(:p3/?)(:p4/?)', function ($p1 = null, $p2 = null, $p3 = null, $p4 = null) { print empty($p1)? "" : '' . "p1: $p1/<br/>"; print empty($p2)? "" : '' . "p2: $p2/<br/>"; print empty($p3)? "" : '' . "p3: $p3/<br/>"; print empty($p4)? "" : '' . "id: $p4<br/>"; }); 

Now the script knows what to do if one of these expressions empty() returns true - prints an empty string.

+1
source

All Articles