How to convert array to URL parameters in PHP

Guanhui
Release: 2023-03-01 07:58:01
Original
4421 people have browsed it

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;);

?>
Copy after login

Output result:

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

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);
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template