Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass an array in GET in PHP?

Tags:

$idArray = array(1,2,3,4); 

can I write this line in HTML?

<form method='POST' action='{$_SERVER['PHP_SELF']}?arr={$idArray}'> 

or should I write:

<form method='POST' action='{$_SERVER['PHP_SELF']}?arr[]={$idArray}'> 

how will it be passed?

how should I handle it in the called page?

thanks !!

like image 975
Yoni Avatar asked Feb 23 '11 23:02

Yoni


People also ask

Can we pass array in Get method?

You can pass arrays to a method just like normal variables. When we pass an array to a method as an argument, actually the address of the array in the memory is passed (reference).

How do you pass an array to a function in PHP?

php // create the 'scores' array $scores = array(9,7,112,89,633,309); // create the 'average' function function average($array){ // set 'total' to 0 $total = 0; foreach($array as $value){ // adds the value of each item in the array, one by one $total += $value; } // calculate the average and return the result return $ ...

Is $_ get an array?

Now that we know how to pass the variables in the URL, we're going to get it in PHP using $_GET. $_GET is a built-in variable of PHP which is an array that holds the variable that we get from the URL.

Can we pass array in URL parameter?

You can make use of serialize() and urlencode PHP built-in function to pass an array as URL param. The serialize() function will return a sequence of bits for the input given and the urlencode will again encode the values as well the special characters available in it.


2 Answers

If you want to pass an array as parameter, you would have to add a parameter for each element. Your query string would become:

?arr[]=1&arr[]=2&arr[]=3&arr[]=4 

As others have written, you can also serialize and unserialize the array.

But do you really have to send the data to the client again? It looks like you just need a way to persist the data between requests.

In this case, it is better imo to use sessions(docs). This is also more secure as otherwise the client could modify the data.

like image 199
Felix Kling Avatar answered Oct 01 '22 03:10

Felix Kling


Use serialize and unserialize PHP function. This function giving you storable (string) version of array type. For more infomation about usage read http://php.net/manual/en/function.serialize.php and http://www.php.net/manual/en/function.unserialize.php

like image 32
Svisstack Avatar answered Oct 01 '22 02:10

Svisstack