Last active
December 15, 2015 21:59
-
-
Save Trainmaster/5330082 to your computer and use it in GitHub Desktop.
Extract array values by html array notation.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function getInputValueByName($name, $data) { | |
if (strpos($name, '[]') !== false) { | |
$name = str_replace('[]', '', $name); | |
} | |
$parts = explode('[', $name); | |
$value = $data; | |
foreach ($parts as $part) { | |
$part = rtrim($part, ']'); | |
if (isset($value[$part])) { | |
$value = $value[$part]; | |
} else { | |
return null; | |
} | |
} | |
return $value; | |
} | |
$array = array('foo' => 'bar', | |
'baz' => array(1, 2, 3, 'foobar' => 'hello world')); | |
print '<pre>'; | |
var_dump(getInputValueByName('foo', $array)); | |
var_dump(getInputValueByName('bar', $array)); | |
var_dump(getInputValueByName('bar[]', $array)); | |
var_dump(getInputValueByName('bar[0]', $array)); | |
var_dump(getInputValueByName('bar[foobar]', $array)); | |
var_dump(getInputValueByName('baz', $array)); | |
var_dump(getInputValueByName('baz[]', $array)); | |
var_dump(getInputValueByName('baz[0]', $array)); | |
var_dump(getInputValueByName('baz[foobar]', $array)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment