Last Updated: February 25, 2016
·
1.085K
· raphaelstolt

Turn a string structure into an array structure

In case you want to turn a string structure into an array structure, the following code snippet might come in handy (which doesn't use the ugly reference operator).

<?php 
$structure = 'a/b/c = 14';
list($structure, $value) = explode('=', $structure);

$structureElements = explode('/', trim($structure));
$data = trim($value);

foreach (array_reverse($structureElements) as $key) {
    $data = array($key => $data);
}

Which results in the following array structure:

array(1) {
  'a' =>
  array(1) {
    'b' =>
    array(1) {
      'c' =>
      int(14)
    }
  }
}

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Related Tags
#php
Did you know?

PHP applications still send a browser full of JavaScript. Hardening the server does not inventory the payment, analytics, and plugin scripts that run after the HTML is delivered.

Security insights from Cside