4

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

5

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];

5
  • Thanks, where can i find some documentation to your code?
    – JTC
    Commented May 2, 2014 at 9:30
  • It's mentioned in the documentation on array access syntax
    – Andy Hunt
    Commented May 2, 2014 at 9:39
  • 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
    Commented May 2, 2014 at 9:58
  • 1
    Yes, but only in PHP 5.4 and beyond.
    – Andy Hunt
    Commented 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.php
    – bdsl
    Commented Jun 29, 2020 at 22:28
2

Other elegant solution:

list($type, ) = explode("/", $route);

I think it's the best one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.