Skip to content

Instantly share code, notes, and snippets.

@anjan011
Last active September 20, 2019 02:58
Show Gist options
  • Save anjan011/a9789eb7ecb59e1c0f02 to your computer and use it in GitHub Desktop.
Save anjan011/a9789eb7ecb59e1c0f02 to your computer and use it in GitHub Desktop.
php: generate html hidden input elements from a php array
<?php
/**
* Convert an array of data into a list of html hidden input fields, using the
* array keys as name and values a input values.
*
* @param array $data Array of data
* @param string $namePrefix Name prefix for hidden controls
*
* @return string
*/
function generateHiddenInputsFromArray( $data = array(), $namePrefix = '' ) {
if(!is_array($data) || empty($data)) {
return '';
}
$html = "";
$namePrefix = trim($namePrefix);
if ( is_array( $data ) && !empty($data) ) {
foreach ( $data as $key => $value) {
$keyEsc = htmlentities($key);
if($namePrefix != '') {
$keyEsc = $namePrefix."[{$keyEsc}]";
}
if(is_array($value)) {
$html .= generateHiddenInputsFromArray($value,$keyEsc);
} else {
$valueEsc = htmlentities($value);
$html .= "<input type='hidden' name='{$keyEsc}' value='{$valueEsc}' />".PHP_EOL;
}
}
}
return $html;
}
@mpyw
Copy link

mpyw commented Sep 20, 2019

Simpler Version

For Pure PHP:

<?php

function buildHiddenInputs(array $data): array
{
    $pairs = explode('&', http_build_query($data, '', '&'));

    $inputs = [];
    foreach ($pairs as $pair) {
        [$key, $value] = explode('=', $pair);

        $inputs[] = sprintf(
            '<input type="hidden" name="%s" value="%s">',
            htmlspecialchars(urldecode($key), ENT_QUOTES, 'UTF-8'),
            htmlspecialchars(urldecode($value), ENT_QUOTES, 'UTF-8')
        );
    }

    return $inputs;
}

For Laravel:

<?php

use Illuminate\Support\HtmlString;

function buildHiddenInputs(array $data): array
{
    $pairs = explode('&', http_build_query($data, '', '&'));

    $inputs = [];
    foreach ($pairs as $pair) {
        [$key, $value] = explode('=', $pair);

        $inputs[] = new HtmlString(sprintf(
            '<input type="hidden" name="%s" value="%s">',
            e(urldecode($key)),
            e(urldecode($value))
        ));
    }

    return $inputs;
}

@anjan011
Copy link
Author

@mpyw thanks mate. It really simplifies it a lot comparing to original code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment