1
\$\begingroup\$

I have an array like this

$list = [];

$list[] = [
    "name" => "bill gates",
    "os" => "windows"
];

$list[] = [
    "name" => "steve jobs",
    "os" => "mac"
];

$list[] = [
    "name" => "linus torvals",
    "os" => "linux"
];

And the I will output this

bill gates > windows, steve jobs > mac, linus torvals > linux

In order to do that, this is what I do

$sentence_parts = [];

foreach($list as $item)
{
    $sentence_parts[] = implode(" > ", $item);
}

$sentence = implode(", ", $sentence_parts);

echo $sentence;

It works, but I feel that maybe I could write a much simpler code. Is there a way to minifiy the code? Maybe a one liner?

\$\endgroup\$

1 Answer 1

2
\$\begingroup\$

I don't think there's anything wrong with your code. It is easy to read, and it does what it needs to do. Why would you want to "minify" that?

Of course it is possible to use a one liner. Something like this:

$sentence = implode(', ', (array_map(function ($item) { return implode(' > ', $item); }, $list)));

See this PHP Fiddle. This uses array_map() to combine the name and OS, with an anonymous function, but to be honest, I find it ugly and I prefer your code. All I did was pack your foreach loop into an array_map() function. This one liner and your code are basically equivalent when executed.

Some general guidelines I always give to my students are:

  • Write your code for a human, not for a computer.
  • Seemingly shorter code might end up being longer once interpreted or compiled.
  • Longer, more explicit, code does often not take any longer to execute.
  • Writing explicit, easily readable code, can give you new insights and is easier to refactor.
\$\endgroup\$
1
  • \$\begingroup\$ Thanks for yout insights. I really liked the phrase "Write your code for a human, not for a computer" \$\endgroup\$ Jan 3, 2022 at 15:22

Your Answer

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

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