Ing. Michal Hudak
Ing. Michal Hudak

Reputation: 5612

Convert an associative array into a string of HTML element attribute assignments

I want to convert array values into string. What should I use to join them as presented in goal?

Should I use serialize() or implode() or http_build_query() or array_walk() ?

$attributes = array(
    'autocomplete' => 'off',
    'class' => 'email',
    'id' => 'myform'
);

echo http_build_query($attributes, '', '" ');

// output
autocomplete=off" class=email" id=myform

Goal:

// output 
autocomplete="off" class="email" id="myform"

Edit:

I used array_walk() to gain goal

function myfunction($value, $key) {
    echo $key . '=" ' . $value . ' " ';
}

array_walk($atributes, "myfunction");

Upvotes: 0

Views: 312

Answers (5)

mickmackusa
mickmackusa

Reputation: 47894

If you are building HTML element attribute declarations with quotes, you should probably encode entities which can interfere with document validity.

How you loop is less important, find a style that you are comfortable with and will be able to maintain in the future.

Code: (Demo)

echo implode(
         ' ',
         array_map(
             fn($k, $v) => sprintf(
                 '%s="%s"',
                 $k,
                 htmlspecialchars(
                     $v,
                     ENT_QUOTES,
                     'UTF-8'
                 )
             ),
             array_keys($attributes),
             $attributes
         )
      );

Input:

$attributes = array(
    'autocomplete' => 'off',
    'class' => 'email',
    'id' => 'myform',
    'value' => 'foo "fizz buzz" bar',
);

Output:

autocomplete="off" class="email" id="myform" value="foo "fizz buzz" bar"

Upvotes: 0

Ing. Michal Hudak
Ing. Michal Hudak

Reputation: 5612

Used array_walk() to gain goal

function myfunction($value, $key) {
    echo $key . '="' . $value . '" ';
}

array_walk($atributes, "myfunction");

Upvotes: 0

Josh Harrison
Josh Harrison

Reputation: 5994

It looks like you want to combine these into a string for outputting on an HTML tag.

This reusable function should produce your desired result:

function get_attribute_string($attr_array) {
    $attributes_processed = array();
    foreach($attr_array as $key => $value) {
        $attributes_processed[] = $key . '="' . $value . '"';
    }

    return implode($attributes_processed, ' ');
}

$atributes = array(
    'autocomplete' => 'off',
    'class' => 'email',
    'id' => 'myform'
);

// this string will contain your goal output
$attributes_string = get_attribute_string($atributes);

P.S. atributes should have three Ts - attributes - mind this doesn't catch you out!

Upvotes: 0

h2ooooooo
h2ooooooo

Reputation: 39532

If you want to make sure that you'll get exactly the same array back, you have to use serialize (as it'll keep variable types) and unserialize to get your data back. Alternately, json_decode and json_encode work as well (but only maintains simple types as int/float/string/boolean/NULL). The data will be larger than implode and http_build_query, though.

Examples:

Consider the following array:

$array = array(
    'foo' => 'bar',
    'bar' => false,
    'rab' => null,
    'oof' => 123.45
);

serialize/unserialize:

<?php
    var_dump( unserialize( serialize($array) ) );
    /*
        array(4) {
            ["foo"] => string(3) "bar"
            ["bar"] => bool(false)
            ["rab"] => NULL
            ["oof"] => float(123.45)
        }
    */
?>

implode/explode:

<?php
    var_dump( explode('&', implode('&', $array) ) );
    /*
        array(4) {
            [0] => string(3) "bar"
            [1] => string(0) ""
            [2] => string(0) ""
            [3] => string(6) "123.45"
        }
    */
?>

json_encode/json_decode:

<?php
    var_dump( json_decode( json_encode($array) , true) );
    /*
        array(4) {
            ["foo"] => string(3) "bar"
            ["bar"] => bool(false)
            ["rab"] => NULL
            ["oof"] => float(123.45)
        }
    */
?>

http_build_query/parse_str:

<?php
    parse_str( http_build_query($array) , $params);
    var_dump( $params );
    /*
        array(3) {
            ["foo"] => string(3) "bar"
            ["bar"] => string(1) "0"
            ["oof"] => string(6) "123.45"
        }
    */
?>

DEMO

Upvotes: 2

The http_build_query is the best option here since you have key=>value combinations

Upvotes: 1

Related Questions