Parse query string into an array
You want the parse_str
function, and you need to set the second parameter to have the data put in an array instead of into individual variables.
$get_string = "pg_id=2&parent_id=2&document&video";
parse_str($get_string, $get_array);
print_r($get_array);
PHP parse query string to associative array
Thanks to Dharman
parse_str()
worked as I wanted. However parse_str()
does not return the parsed variables. It just creates the variable in current scope.
parse QueryString in javascript
A few suggestions - consider using window.location.search
to access the query string directly.
Also, you might want to factor in scenarios where "arrays" exist in your query string (ie multiple values sharing the same key). One way to handle that might be to return an array of values found for a key, in the data
object that you return.
For more detail, see the comments in this updated version of the function:
function parseQueryString() {
// Use location.search to access query string instead
const qs = window.location.search.replace('?', '');
const items = qs.split('&');
// Consider using reduce to create the data mapping
return items.reduce((data, item) => {
const [rawKey, rawValue] = item.split('=');
const key = decodeURIComponent(rawKey);
const value = decodeURIComponent(rawValue);
// Sometimes a query string can have multiple values
// for the same key, so to factor that case in, you
// could collect an array of values for the same key
if(data[key] !== undefined) {
// If the value for this key was not previously an
// array, update it
if(!Array.isArray(data[key])) {
data[key] = [ data[key] ]
}
data[key].push(value)
}
else {
data[key] = value
}
return data
}, {})
}
Parse just one query string parameter into Javascript array
Assuming that the order of your query strings aren't always going to be known and that you have to support finding 'q' anywhere;
// substring(1) to skip the '?' character
var queryStrings = window.location.search.substring(1).split('&');
var qArray;
for (var i = 0; i < queryStrings.length; i++) {
if (queryStrings[i].substring(0, 2) === 'q=') {
qArray = queryStrings[i].substring(2).split('+');
break;
}
}
Related Topics
Is There a Use-Case For Singletons With Database Access in PHP
How to Get a File'S Extension in PHP
How to Reindex an Array in PHP But With Indexes Starting from 1
Open_Basedir Restriction in Effect. File(/) Is Not Within the Allowed Path(S):
PHP Function to Generate V4 Uuid
How Can One Check to See If a Remote File Exists Using PHP
How to Read If a Checkbox Is Checked in PHP
Working With Large Numbers in PHP
How to Use Pdo to Fetch a Results Array in PHP
Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (Codeigniter + Xml-Rpc)
Apache Shows PHP Code Instead of Executing It
A Simple Program to Crud Node and Node Values of Xml File
Creating Default Object from Empty Value in PHP