PHP - contents of an array of queries with point syntax

Does anyone see something wrong with the following function? ( Edit : no, I don’t think that something is wrong, I just check, as this will be inserted into a very common code path.)

function getNestedVar(&$context, $name) { if (strstr($name, '.') === FALSE) { return $context[$name]; } else { $pieces = explode('.', $name, 2); return getNestedVar($context[$pieces[0]], $pieces[1]); } } 

This essentially converts:

 $data, "fruits.orange.quantity" 

in

 $data['fruits']['orange']['quantity'] 

In context, this is for the form utility that I create in Smarty. I also need a name for the form, so I need a line in the form based on the key and cannot directly access the Smarty variable in Smarty.

+4
source share
7 answers

Try an iterative approach:

 function getNestedVar(&$context, $name) { $pieces = explode('.', $name); foreach ($pieces as $piece) { if (!is_array($context) || !array_key_exists($piece, $context)) { // error occurred return null; } $context = &$context[$piece]; } return $context; } 
+7
source

Take a look at this: https://gist.github.com/elfet/4713488

 $dn = new DotNotation(['bar'=>['baz'=>['foo'=>true]]]); $value = $dn->get('bar.baz.foo'); // $value == true $dn->set('bar.baz.foo', false); // ['foo'=>false] $dn->add('bar.baz', ['boo'=>true]); // ['foo'=>false,'boo'=>true] 

And this class also has PHPUnit tests.

+1
source

I do not see anything wrong with this code. I also checked it.

Does this answer your question?

Edit: This is IMHO a little better. It does not use recursion and returns null if it accesses a child without an array.

 function getNestedVar(array $array, $name) { $name = explode('.', $name); foreach($name as $namePart) { if (is_array($array)) return null; if (!isset($array[$name])) return null; $array = $array[$name]; } return $array; } 

Greetings

0
source

How deep will this nesting be? PHP has a recursion limit, it seems ok. 2 ^ 16. I just tested it and at the depth of recursion 65420 PHP (5.2.9) was silent (no errors).

0
source

In its current form, errors / warnings are not displayed if one or more elements do not exist

 error_reporting(E_ALL|E_STRICT); ini_set('display_errors', 1); $x = array(); getNestedVar($x, '1.2.3.4'); echo 'done.'; 

(verified using php 5.3.1 / win32).
For some reason, accessing a nonexistent element in getNestedVar($context[$pieces[0]]... does not raise a warning, which makes it very difficult to debug and search, for example, a typo.

0
source

Why don't you just use html .. name="fruit[orange]" enough .. to create an array.

0
source

Take a look @ http://github.com/projectmeta/Stingray

Allows reading and writing an array through dot notation / syntax.

Example: http://github.com/projectmeta/Stingray#example-usage

0
source

Source: https://habr.com/ru/post/1301662/


All Articles