xd3v
xd3v

Reputation: 159

How can I parse a URL into an associative array?

I have a URL like http://example.com/size/large/color/red. How can I convert the URL into an associate array so that I end up with:

$my_array("size" => "large", "color" => "red");

Bear in mind, that the URL could look like http://example.com/color/red/size/large/type/round. So basically, the keys and values could be anything. But they key will always be followed by the value.

Upvotes: 0

Views: 605

Answers (2)

rid
rid

Reputation: 63580

You can extract the parts that make up the URL, then loop through them 2 by 2 and assign the first as the key and the second as the value.

$url = 'http://example.com/color/red/size/large/type/round';
$my_array = array();
$parts = explode('/', $url);
for ($i = 3, $len = count($parts); $i < $len; $i += 2)
{
    $my_array[$parts[$i]] = $parts[$i + 1];
}

This would produce:

Array
(
    [color] => red
    [size] => large
    [type] => round
)

Upvotes: 1

user142162
user142162

Reputation:

$url = 'http://example.com/size/large/color/red';

$path = trim(parse_url($url, PHP_URL_PATH), '/');
$path_chunks = preg_split('/\/+/', $path);

$arr = array();

for($i = 0, $count = count($path_chunks); $i < $count; $i += 2)
{
   $arr[$path_chunks[$i]] = $path_chunks[$i + 1];
}

Upvotes: 4

Related Questions