I am building an application where some informations are stored in a key/value string.
tic/4/tac/5/toe/6
Looking for some nice solutions to extract data from those strings I happened here and after a while I got this solution:
$tokens = explode('/', $token);
if (count($tokens) >= 2) {
list($name, $val) = $tokens;
$props[$name] = $val;
}
if (count($tokens) >= 4) {
list(, , $name, $val) = $tokens;
$props[$name] = $val;
}
if (count($tokens) >= 6) {
list(, , , , $name, $val) = $tokens;
$props[$name] = $val;
}
// ... and so on
freely inspired by smassey's solution
This snippet will produce the following kinds of arrays:
$props = [
'tic' => 4,
];
or
$props = [
'tic' => 4,
'tac' => 5,
];
or
$props = [
'tic' => 4,
'tac' => 5,
'toe' => 6,
];
my two cents