Ivan
Ivan

Reputation: 2481

Count how many times a key appears in a querystring


Suppose that I have a querystring like this:

?s=1&s=1&s=1

How do I count how many times the key "s" appears (no matter the value) ? I tried with

count($_GET['s'])

but it always returns 1.

Thanks in advance!

Upvotes: 0

Views: 143

Answers (2)

BenM
BenM

Reputation: 53198

To count how many times s= occurs in the query string, you can do this:

$query_string = $_SERVER['QUERY_STRING'];
$occurs = substr_count($query_string, 's=');
echo $occurs;

It is better to follow @hsz's answer though.

Upvotes: 3

hsz
hsz

Reputation: 152216

Result of count($_GET['s']) is correct, because with ?s=1&s=1&s=1 you overwrite s parameter with the last value. If you want to pass an array, do it with:

?s[]=1&s[]=1&s[]=1

then count will returns 3 as expected.

Upvotes: 1

Related Questions