The Codesee The Codesee - 4 months ago 7
HTML Question

Get URL Variable From Array

I am trying to get the URL variable

ID
from a list of objects in an array and display them.




Current Code:

$display = print_r($array);
echo $display;


Output:

Array ( [0] => https://example.com?ID=435 [1] => https://example.com?ID=53 [2] => https://example.com?ID=5 [3] => https://example.com?ID=25 )





I would like the display each URL variable
ID
from the array inside a
<div>
element:

<div>435</div>
<div>53</div>
<div>5</div>
<div>25</div>


I have tried to do this using the following code but no luck:

foreach($display as $display2) {
echo '<div>'.$_GET['ID'].'</div>';
}

Answer

The $_GET super global is for accessing query-string values from the current request, not for reading them out of an arbitrary url stored in a string.

But fret not, PHP's standard library has functions to help, namely parse_url() and parse_str()

foreach($display as $url) {
   $queryString = parse_url($url, PHP_URL_QUERY)
   parse_str($queryString, $parameters)
   echo '<div>'.$parameters['ID'].'</div>';
}
Comments