For example I have this code:
$route = 'product/category';
//variable overload
$type = explode('/',$route);
$type = $type[1];
My thinking behind this is that I actually don't need unique variable name for exploded variable, so why not to overwrite?
Is this really bad concept? Or is there some more elegant way to write this?
2 Answers 2
No, it's absolutely not bad. All you're doing here is assigning a new value to a variable. It has no special name.
As for more elegantly writing it, you could write the following as of PHP 5.4:
$type = explode("/", $route)[0];
-
Thanks, where can i find some documentation to your code?JTC– JTC2014年05月02日 09:30:20 +00:00Commented May 2, 2014 at 9:30
-
-
According to your link i have one off-topic question, so if I call php function, which returns array, i can specifically call array key which I want to get the same way as your code?JTC– JTC2014年05月02日 09:58:08 +00:00Commented May 2, 2014 at 9:58
-
1Yes, but only in PHP 5.4 and beyond.Andy Hunt– Andy Hunt2014年05月02日 10:14:29 +00:00Commented May 2, 2014 at 10:14
-
From the PHP manual: "As of PHP 5.4 it is possible to array dereference the result of a function or method call directly. Before it was only possible using a temporary variable." php.net/manual/en/language.types.array.phpbdsl– bdsl2020年06月29日 22:28:29 +00:00Commented Jun 29, 2020 at 22:28
Other elegant solution:
list($type, ) = explode("/", $route);
I think it's the best one.