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?

asked May 2, 2014 at 9:05

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

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

Other elegant solution:

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

I think it's the best one.

answered May 3, 2014 at 7:08

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.