PHP multidimensional array to form hidden inputs

March 22, 2019
/**
 * Corvert array data to hidden inputs
 * to pass as form data
 *
 * Example: [data => [sub1 => 1, sub2 => 2]]
 * 
 * 
 *
 * @author Ivan Gospodinow
 * @see http://ivangospodinow.com/?p=455
 * @param array $array
 * @param [array | string] $exclude
 * @return string
 */
function arrayToHiddenInput(array $array, $exclude = null)
{
    $hiddens = [];
    $strParams = urldecode(http_build_query($array));

    if (!empty($strParams)) {
        $params = explode('&', $strParams);
        foreach ($params as $param) {
            list($name, $value) = explode('=', $param);

            if (is_array($exclude) && in_array($name, $exclude)) {
                continue;
            } else if ($name == $exclude) {
                continue;
            }

            $hiddens[] = sprintf(
                '',
                $name,
                $value
            );
        }
    }

    return implode(PHP_EOL, $hiddens);
}

Example:

echo arrayToHiddenInput(['data' => ['sub1' => 1, 'sub2' => 2]]);

Result:


Simple as that

posted in php by Ivan Gospodinow

Follow comments via the RSS Feed | Leave a comment | Trackback URL

Leave Your Comment


Warning: Use of undefined constant XML - assumed 'XML' (this will throw an Error in a future version of PHP) in /home/c2kblate/sites/ivangospodinow.com/wp-content/plugins/wp-syntaxhighlighter/wp-syntaxhighlighter.php on line 1048
 
Powered by Wordpress and MySQL. Theme by Shlomi Noach, openark.org