I'm trying to access a array via its index, but I need to get this from the query string.
I've tried:
$var = $_GET['id'];
echo $xml->subway->line[$var]->name;
That doesn't work. But this does:
echo $xml->subway->line[0]->name;
try this:
$var = isset($_GET['id']) ? (int)$_GET['id'] : false;
if ($var !== false && isset($xml->subway->line[$var]) {
echo $xml->subway->line[$var]->name;
} else {
echo 'Your problem is either "id" not being in $_GET or $xml object does not have line with that index';
var_dump($_GET); //see what is 'id'
}
Everytime you are getting item from an array by index you should check if it is set first to avoid errors like this.
It's likely that your $_GET
variable is coming back as a string
instead of an integer
so PHP will be assuming the index doesn't exist. Try type casting it as
$var = (int)$_GET['id'];
Which forces PHP to treat the $_GET
as an integer
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.