Electricmonk

Ferry Boender

Programmer, DevOpper, Open Source enthusiast.

Blog

PHP: Directly Assign Exploded Parts To Variables

Saturday, February 11th, 2006

Many languages (amongst them Python and Perl) provide a way to directly assign the parts of a split string to variables. The syntax usually used is something like:

firstname, lastname = "John,Doe".split(",");

or something similar. PHP does not support such a syntax. The programmer instead has to perform all spliting, checking and assigning himself.

This little snippet of code allows you to directly assign parts of an exploded string to variables or -if the exploding does not match the number of variables- assign defaults.

function explodeAssign($string, $seperator, $vars) {
    $temp = explode($seperator, $string);
    if (count($temp) != count($vars)) {
        return(false);
    } else {
        for ($i = 0; $i != count($temp); $i++) {
            $vars[$i] = $temp[$i];
        }
        return(true);
    }
}

$string is the string you want to explode.
$seperator is the seperator you want to use.
$vars is an array containing pass-by-reference variables. (this is important, otherwise it won’t work)

Some examples:

if (!explodeAssign(
  "ferry,boender,25",
  ',',
  array(&$firstname, &$lastname, &$age))) {
    $firstname = "John";
    $lastname = "Doe";
    $age = "20";
}

print("Hello $firstname $lastname. You are $age years old.n");

if (!explodeAssign(
  "ferry,boender",
  ',',
  array(&$firstname, &$lastname, &$age))) {
    $firstname = "John";
    $lastname = "Doe";
    $age = "20";
}

print("Hello $firstname $lastname. You are $age years old.n");

The output of which will be:

Hello ferry boender. You are 25 years old.
Hello John Doe. You are 20 years old.

Hope it’s useful.

Update: Not as useful as I thought, as PHP has a list() language construct:

list($firstname, $lastname, $age) = explode(",", "ferry,boender,25"));
print($firstname); // ferry

The text of all posts on this blog, unless specificly mentioned otherwise, are licensed under this license.