PHP

Converting Associative Array to HTML Attributes or Query String

Convert associative arrays into string formats ideal for HTML attributes or URL query parameters. This ensures proper encoding and handles boolean attributes gracefully.

<?php
$attributes = [
    'id' => 'myButton',
    'class' => 'btn btn-primary',
    'data-toggle' => 'modal',
    'data-target' => '#myModal',
    'disabled' => true, // Boolean true becomes 'disabled'
    'autofocus' => false, // Boolean false is ignored
    'aria-label' => 'Close',
    'style' => 'font-size: 16px;',
    'empty_val' => '',
    'null_val' => null
];

/**
 * Converts an associative array into a string of HTML attributes.
 * Handles boolean true as a standalone attribute and skips false/null/empty string values.
 */
function arrayToHtmlAttributes(array $attrs): string {
    $htmlParts = [];
    foreach ($attrs as $key => $value) {
        // Skip null, false, and empty string values for HTML attributes
        if ($value === null || $value === false || $value === '') {
            continue;
        }

        $escapedKey = htmlspecialchars((string)$key, ENT_QUOTES, 'UTF-8');

        if ($value === true) {
            // For boolean attributes like 'disabled', 'checked'
            $htmlParts[] = $escapedKey;
        } else {
            $escapedValue = htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
            $htmlParts[] = "{$escapedKey}=\"{$escapedValue}\"";
        }
    }
    return implode(' ', $htmlParts);
}

// Example 1: HTML Attributes conversion
$htmlAttrs = arrayToHtmlAttributes($attributes);
echo "HTML Attributes: <button {$htmlAttrs}>Click me</button>

";
// Expected Output: HTML Attributes: <button id="myButton" class="btn btn-primary" data-toggle="modal" data-target="#myModal" disabled aria-label="Close" style="font-size: 16px;">Click me</button>


$queryParams = [
    'page' => 2,
    'sort' => 'name',
    'filter' => [
        'status' => 'active',
        'category' => 'books with spaces'
    ],
    'include_null' => null,
    'include_empty' => ''
];

/**
 * Converts an associative array into a URL query string.
 * Uses PHP's built-in http_build_query for robust encoding.
 */
function arrayToQueryString(array $params): string {
    // http_build_query automatically handles URL encoding and nested arrays
    // It also ignores null values by default, and includes empty strings.
    return http_build_query($params);
}

// Example 2: Query String conversion
$queryString = arrayToQueryString($queryParams);
echo "Query String: ?{$queryString}
";
// Expected Output: Query String: ?page=2&sort=name&filter%5Bstatus%5D=active&filter%5Bcategory%5D=books+with+spaces&include_empty=
?>
How it works: This snippet provides two utility functions for converting associative arrays into string representations common in web development. `arrayToHtmlAttributes` transforms an array into a space-separated string of HTML attributes, correctly handling boolean attributes (like `disabled`) and skipping null, false, or empty string values. `arrayToQueryString` leverages PHP's `http_build_query` to create a robust, URL-encoded query string from an array, which is essential for generating dynamic URLs with parameters, handling nested arrays and special characters automatically.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs