Using PHP's List
As a programmer you're going to be asked to deal with other people's data. Hopefully, it's in a nice easy to use format like JSON, XML, or properly normalized SQL tables. Occasionally, some asshole is going to do something lazy like create a single field that contains multiple values in the same field (I ran into this problem this week) using some kind of delimiter.
PHP has the function explode
that allows you to take an arbitrary piece of text and break it into an array based on a delimiter. For example, if we had the text value1_value2
and we wanted it broken based on the _
we would write.
$values = explode('_', 'value1_value2');
This works well, but if you have to keep referring to those values you either have to use $values[0]
over and over again or save it to a variable. Saving it to the variable is the cleanest solution because it would create an easy to remember name and therefore produce easier to read code. This means our example looks more like this:
$values = explode('_', 'value1_value2');
$values1 = $values[0];
$values2 = $values[1];
This works and it works well but PHP has an even better way to do this in a single line.
list($value1, $value2) = explode("_", 'value1_value2');
It may not make a huge difference in this example but having that one line is a lot better than having line after line of $valuesn = $values[n-1]
.
Scott Keck-Warren
Scott is the Director of Technology at WeCare Connect where he strives to provide solutions for his customers needs. He's the father of two and can be found most weekends working on projects around the house with his loving partner.
Top Posts
- Working With Soft Deletes in Laravel (By Example)
- Fixing CMake was unable to find a build program corresponding to "Unix Makefiles"
- Upgrading to Laravel 8.x
- Get The Count of the Number of Users in an AD Group
- Multiple Vagrant VMs in One Vagrantfile
- Fixing the "this is larger than GitHub's recommended maximum file size of 50.00 MB" error
- Changing the Directory Vagrant Stores the VMs In
- Accepting Android SDK Licenses From The OSX Command Line
- Fixing the 'Target class [config] does not exist' Error
- Using Rectangle to Manage MacOS Windows