Skip to content

Instantly share code, notes, and snippets.

@eric1234
Created June 18, 2013 01:45
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eric1234/5802030 to your computer and use it in GitHub Desktop.
Save eric1234/5802030 to your computer and use it in GitHub Desktop.
Convert data structure to hidden input fields

Purpose

Useful when you want to pass on a complex data structure via a form.

Examples

Basic Associative Array

echo array_to_input(array('foo' => 'bar', 'cat' => 'dog'));

Will output:

<input type="hidden" value="bar" name="foo">
<input type="hidden" value="dog" name="cat">

Associative Array with Nested Indexed Array

echo array_to_input(array('foo' => 'bar', 'cat' => 'dog', 'list' => array('a', 'b', 'c')));

Will output:

<input type="hidden" value="bar" name="foo">
<input type="hidden" value="dog" name="cat">
<input type="hidden" name="list[]" value="a">
<input type="hidden" name="list[]" value="b">
<input type="hidden" name="list[]" value="c">

Associative Array with Nested Associative Array

echo array_to_input(array('foo' => array('bar' => 'baz', 'a' => 'b'), 'cat' => 'dog'));

Will output:

<input type="hidden" value="baz" name="foo[bar]">
<input type="hidden" value="b" name="foo[a]">
<input type="hidden" value="dog" name="cat">

Go Crazy

echo array_to_input(array('a' => array('b' => array('c' => array('d' => 'e')))));

Will output:

<input type="hidden" value="e" name="a[b][c][d]">
<?php
# https://gist.github.com/eric1234/5802030
function array_to_input($array, $prefix='') {
if( (bool)count(array_filter(array_keys($array), 'is_string')) ) {
foreach($array as $key => $value) {
if( empty($prefix) ) {
$name = $key;
} else {
$name = $prefix.'['.$key.']';
}
if( is_array($value) ) {
array_to_input($value, $name);
} else { ?>
<input type="hidden" value="<?php echo $value ?>" name="<?php echo $name?>">
<?php }
}
} else {
foreach($array as $item) {
if( is_array($item) ) {
array_to_input($item, $prefix.'[]');
} else { ?>
<input type="hidden" name="<?php echo $prefix ?>[]" value="<?php echo $item ?>">
<?php }
}
}
}
@james-jlo-long
Copy link

This breaks if you have an array of associated arrays, a bit like this:

array(
    array('one' => 1, 'two' => 2),
    array('one' => 10, 'two' => 20)
);

You just need to pass the array item in that second foreach:

function array_to_input($array, $prefix='') {
  if( (bool)count(array_filter(array_keys($array), 'is_string')) ) {
    // ...
  } else {
    foreach($array as $i => $item) {
      if( is_array($item) ) {
        array_to_input($item, $prefix.'['.$i.']');
      } else { ?>
        <input type="hidden" name="<?php echo $prefix ?>[<?php echo $i ?>]" value="<?php echo $item ?>">
      <?php }
    }
  }
}

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