Reputation: 1425
I trying to achieve something like this in Slim PHP:
page/p1/p2/p3/p4
I want that If I leave out params from the right(obviously) then I want to do my stuff based on whatever params I've 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 is whenever i remove a param from the end, it prints 1
for every param I remove.
why is it doing so?
what am I doing wrong here?
Upvotes: 0
Views: 2474
Reputation: 38
Since you omitted the second part of the ternary (what should print if the test statement returns true
), the ternary statement returns what the test expression evaluates to. That result is then printed out.
When you omit the last parameter in the route, the test expression results to true
, but since you do not define what to do in this case, true
is returned and 1
is printed out.
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 should one of those empty()
expressions return true -- print an empty string.
Upvotes: 1