Home  >  Article  >  Backend Development  >  How to convert array to URL parameters in PHP

How to convert array to URL parameters in PHP

Guanhui
GuanhuiOriginal
2020-05-14 13:57:504403browse

How to convert array to URL parameters in PHP

How to convert an array into a URL parameter in PHP

1. Use the PHP built-in function "http_build_query()" to convert a string into a URL parameter;

Usage example:

<?php
$data = array(
    &#39;foo&#39; => &#39;bar&#39;,
    &#39;baz&#39; => &#39;boom&#39;,
    &#39;cow&#39; => &#39;milk&#39;,
    &#39;php&#39; => &#39;hypertext processor&#39;
);

echo http_build_query($data) . "\n";
echo http_build_query($data, &#39;&#39;, &#39;&amp;&#39;);

?>

Output result:

foo=bar&baz=boom&cow=milk&php=hypertext+processor
foo=bar&amp;baz=boom&amp;cow=milk&amp;php=hypertext+processor

2. Use loops to splice the arrays according to the URL parameter rules, and use "=" to splice the array units for keys and values. Just use "&" to splice.

Simple example:

function array_to_url_prarm($array)
{
  $prarms = [];

  foreach ($array as $key => $val) {
    $prarms[] = $key . &#39;=&#39; . str_replace(&#39; &#39;, &#39;+&#39;, $val);
  }

  return implode(&#39;&&#39;, $prarms);
}

Recommended tutorial: "PHP Tutorial"

The above is the detailed content of How to convert array to URL parameters in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn