Problem:
You want to pass an array from one page to another by URL as parameter. The array could be a one dimensional or a mufti-dimensional array.
Solution:
To pass array by URL, we have to create URL-encoded query string of that array and then pass via URL. We can do it in two ways-
Method 1: Using http_build_query() function
Step 1: Prepare the array to pass by URL
http_build_query() function can convert an array to its equivalent URL-encoded query string. See the following example-
<?php $data = array('email'=>'test@test.com', array("php","mysql"), 'age'=>28); echo "<a href='page2.php?" . http_build_query($data) . "'>next page</a>"; ?>
[wpdm_file id=103]
How it works:
Taking the elements of the array, http_build_query() function generates their equivalent URL-encoded string. When you run the script & bring mouse over the “next page” link, you’ll see the encoded string something like this-
Step 2: How to receive the array from URL:
In the page2.php page, to retrieve the values, use the array keys in the following way-
<?php echo $_GET['email']; echo "<br />"; echo $_GET[0][0]; echo "<br />"; echo $_GET[0][1]; echo "<br />"; echo $_GET['age']; echo "<br />"; ?>
Note: You can also pass associative array. Not only arrays, you can also send simple string in the same way.
Method 2: Using serialize() and urlencode() functions
Step 1: Prepare the array to pass by URL
urlencode() function can also be used to create an URL-encoded string. But it can’t convert an array to an URL-encoded string. So, at first, we’ll convert the array into its byte stream representation which is a string using serialize() function, then we’ll create an URL-encoded string of that byte stream. See the code below-
<?php $data = array('email'=>'test@test.com', array("php","mysql"), 'age'=>28); echo "<a href='page2.php?str=" . urlencode(serialize($data)) . "'>next page</a>"; ?>
[wpdm_file id=104]
How it works
serialize() function first convert the array to byte stream string, and urlencode() function convert that string to URL-encoded string. When you run the script & bring mouse over the “next page” link, you’ll see the encoded string something like this-
http://localhost/…/page2.php?str=a%3A3%3A%7Bs%3A5%3A%22email%22%3Bs%3A13%3A%22test%40test.com%22%3Bi%3A0%3Ba%3A2%3A%7Bi%3A0%3Bs%3A3%3A%22php%22%3Bi%3A1%3Bs%3A5%3A%22mysql%22%3B%7Ds%3A3%3A%22age%22%3Bi%3A28%3B%7D
Step 2: How to receive the array from URL
In the page2.php page, to retrieve the values from the URL, you’ve to reverse the previous processes.First decode it using urldecode() function, then, use unserialize() function in the following way-
<?php $str_arr = unserialize(urldecode($_GET['str'])); echo $str_arr['email']; echo "<br />"; echo $str_arr[0][0]; echo "<br />"; echo $str_arr[0][1]; echo "<br />"; echo $str_arr['age']; echo "<br />"; ?>
Caution: Remember, you can’t pass more than 2083 characters via URL. So, consider this before passing an array via URL in any of the above methods.