Using explode() to create arrays

MODX logoSay you have a snippet that needs a simple array and want to send the elements of the array in the snippet tag. The PHP explode() function is custom-made for your use case.

You’ve probably seen lots of MODX snippets the use a comma-separated list in one or more properties. You may have wondered how the snippet processes that comma-separated list. In this article we’ll see how it’s done.

 

Using explode()

The explode() function takes a string in the form of a list with some delimiter and converts it to a simple array. The delimiter can be anything (a word, a phrase, or a punctuation mark), but the most common delimiter is a comma. The first argument to explode() specifies the the delimiter (in the form of a string). The second argument is the string with the comma-separated list itself.

In a bit, we’ll add a slight modification to remove extraneous leading or trailing spaces from the array elements, but for now we’ll keep it simple. We’ll send a comma-separated list of usernames to a snippet called ActivateUsers like this:

[code language=”html”]
[[ActivateUsers?
&names=`BobRay,JohnDoe,JaneRoe`
]]
[/code]

In this example, we’ll walk through the listed users and activate each one. Here’s the code:

[code language=”php”]
/* ActivateUsers snippet */
$names = $modx->getOption(‘names’, $scriptProperties, ”);
$nameArray = explode(‘,’, $names);
$output = ”;
foreach ($nameArray as $name) {
/* Get the user */
$currentUser = $modx->getObject(‘modUser’, array(‘username’ => $name));
/* Make sure we have found the user or the code will crash */
if ($currentUser) {
/* Make the user active */
$user->set(‘active’, true);
$user->save();
$output .= ‘<br /> Activated user: ‘ . $name;
} else {
$output .= ‘<br/> Could not find user: ‘ . $name;
}
}

return $output;
[/code]

The actual PHP array created by explode() would look like this:

[code language=”php”]
$nameArray = array(
0 => ‘BobRay’,
1 => ‘JohnDoe’,
2 => ‘JaneRoe’,
);
[/code]

When you use foreach() with a single variable after the as, the variable will always hold the right-hand member of that array element, so the foreach() loop in our code above will process each username in turn.

In our code above, we used two separate variables, $names and $nameArray. We could have used just $names, like this:

[code language=”php”]
$names = $modx->getOption(‘names’, $scriptProperties, ”);
$names = explode(‘,’, $names);

foreach($names as $name) { // etc.
[/code]

This second version will work fine. It’s quicker to write, and it reduces the number of variables used, but PHP will do a little extra work to convert a string variable to an array variable in the second line. You could argue that using $nameArray makes the code more readable and less likely to confuse people who need to understand and/or modify it (including you). Which approach you take is largely a matter of personal preference.

 

When users/clients enter a comma-separated list in a MODX snippet property, it’s natural for them to add a space after the comma — they’ve been doing it for years in written text, and often add the space unconsciously. If you don’t account for this, your code can break when, for example, you try to find a username in the DB but the username with a leading space isn’t there. Since users won’t always add the space, you can’t count on the space being there.

The solution is to always use the trim() function to remove any leading or trailing spaces.

 

Adding array_map() and trim()

Here’s some code that implements the trim function using PHP’s array_map() function:

[code language=”php”]
$names = $modx->getOption(‘names’, $scriptProperties, ”);
$nameArray = array_map(‘trim’, explode(‘,’, $names));
[/code]

 

What’s Happening

In the code above, the comma-separated list of names is sent in the snippet property &names in the tag. In the first line, we get it from the the $scriptProperties array with $modx->getOption().

Once we have the string containing the names, we use explode() to turn it into an array, but we embed the call to explode() in an array_map call to trim any leading or trailing spaces. As we saw in an earlier article, the array_map() function calls the function named in the first argument on the array specified in the second argument and returns the altered array. The code above is roughly equivalent to the code below, but much more elegant (and somewhat more efficient):

[code language=”php”]
$names = $modx->getOption(‘names’, $scriptProperties, ”);
$nameArray = explode(‘,’, $names);
$temp = array();
foreach( $nameArray as $name) {
$temp[] = trim($name);
}
$nameArray = $temp;
unset($temp);
[/code]

Note that the trim() function won’t remove spaces *inside* the string, only at the ends, so a username like ‘Bob Ray’ will retain its space. Trim also removes newlines and tabs from the ends of the string, which is handy if the user does something like this in the tag:

[code language=”html”]
[[ActivateUsers?
&names=`BobRay,
JohnDoe,
JaneRoe`
]]
[/code]

If we were only worried about trailing spaces, we could use rtrim(). For leading spaces, we’d use ltrim(). In this case, we want to remove both leading and trailing spaces, so we use trim(), which trims both ends of the string.

 

Coming Up

What if your snippet needs an associative array? Say you want to send a group of usernames and their associated email addresses in the tag, and turn them into an associative array in the snippet. The answer is to use two separate delimiters and call explode() twice. We’ll see how to do that in the next article.

 


For more information on how to use MODX to create a web site, see my web site Bob’s Guides, or
better yet, buy my book: MODX: The Official Guide.

Looking for quality MODX Web Hosting? Look no further than Arvixe Web Hosting!

Tags: , , | Posted under MODX, MODX | RSS 2.0

Author Spotlight

Bob Ray

Bob Ray is the author of MODX: The Official Guide and over 30 MODX add-on components. He hosts Bob's Guides, a source of valuable information for MODX users, and has been very active in the MODX Forums with over 19,000 posts.

Leave a Reply

Your email address will not be published. Required fields are marked *