PHP Zone

How to Pass the array values on query string in PHP

10 Oct , 2015  

Definition of Array :

An array in PHP is actually an ordered map. A map is a type that associates values to keys. This type is optimized for several different uses; it can be treated as an array, list (vector), hash table (an implementation of a map), dictionary, collection, stack, queue, and probably more. As array values can be other arrays, trees and multidimensional arrays are also possible.

Syntax for Array :

$array = array(
    "foo" => "bar",
    "bar" => "foo",

// as of PHP 5.4
$array = [
    "foo" => "bar",
    "bar" => "foo",

About Query String :

A query string is the portion of a URL where data is passed to a Web application and/or back-end database. The reason we need querystrings is that the HTTP protocol is stateless by design.

In a URL (Uniform Resource Locator), the querystring follows a separating character, usually a question mark (?). Identifying data appears after this separating symbol. For example, consider the following URL:

This produces a list of all the books available from the online bookseller BookFinder4u bearing the author’s name Ernest Hemingway, in reverse chronological order by publication date. The querystring in this example consists of one field or variable, technically called a key in this context (here, it is the word “sort”), followed by an equals sign (=), followed by the value for that key (here, it is the word “date”). Each key and its corresponding value, denoted as an equation, is called a key-value pair. A querystring may contain several key-value pairs. When there is more than one key-value pair, they are typically separated by ampersands (&).

For Example :

How to pass the array values in query string in PayPal checkout URL button,

Here is the code of PayPal Checkout button :

foreach ( $Cart->getItems() as $order_code=>$quantity ) :
  $pname[]= $Cart->getItemName($order_code);
  $item[]= $Cart->getItemPrice($order_code);
<input alt="Check out with PayPal" name="submit" src="" type="image" align="top" />

for the above sample code i have to pass the query string on my action url that is expresscheckout.php?amt=100.,etc…values are coming under the $pname[],$item[],$qty[].

Expecting output in expresscheckout.php

expresscheckout.php?pname=product1,product2&item=item1,item2&qty=1,2,3….like this….

Solution :

Basically, you just need to use PHP’s implode function to turn an array into a comma-separated list. i.e. for the $item array:

$item = array('item1', 'item2');
echo implode(',', $item);

Will output:


So, something like this should print a querystring similar to what you want:

echo 'pname='.implode(',', $pname).
     '&item='.implode(',', $item).
     '&qty='.implode(',', $qty);

, ,