PHP Tip: More useful explode with item list
Manuel Canga

Manuel Canga @manuelcanga

About: Hi!. I am Manuel Canga, a web back-end developer specializing in tailor-made web applications with over 20 years of experience. I am a Zend Certified PHP Engineer and a native Spanish speaker.

Location:
Córdoba, España
Joined:
Nov 27, 2022

PHP Tip: More useful explode with item list

Publish Date: Feb 27 '23
0 0

Securely, you did some item list like this once, didn't you?:

<?php
function to_array(string $allowed_extensions): array {
  $allowed_list = explode(',', $allowed_extensions);
  return  array_map(fn($ext)=> trim($ext), $allowed_list);
}

to_array('.pdf, .odt, .doc'); //['.pdf', '.odt', '.doc']
Enter fullscreen mode Exit fullscreen mode

not bad, but this is better:

<?php
function to_array(string $allowed_extensions): array {
    $allowed_list = str_word_count($allowed_extensions, format: 1, characters: '.');
    return  array_map(fn($ext)=> trim($ext), $allowed_list);
}

to_array('.pdf, .odt, .doc'); //['.pdf', '.odt', '.doc']
Enter fullscreen mode Exit fullscreen mode

Why?, because now you can change list format without changing nothing more. Look!:

to_array('.pdf|.odt|.doc'); //['.pdf', '.odt', '.doc']
to_array('.pdf;.odt;.doc'); //['.pdf', '.odt', '.doc']
Enter fullscreen mode Exit fullscreen mode

Happy coding!

Comments 0 total

    Add comment