PHP / HTML - isset函数 [英] PHP/HTML - isset function

查看:176
本文介绍了PHP / HTML - isset函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对PHP相当陌生,正在为我的公司创建一个网站。我使用了一些我已经获得的代码,但似乎无法使它正常工作 - 任何帮助都将非常感谢!



我有一个变量, $ id ,它标识要在页面上显示的产品类别类型。我首先需要检查id变量是否已设置,如果不是,则将该变量默认为0类。



我拥有的代码如下所示:

  setdefault($ id,0); 

函数setdefault(& $ var,$ default =)
{
if(!isset($ var))
{
$ var = $ default;
}
}

因此,地址为www.website.com/browse .php,我希望它默认为$ id = 0;地址为www.website.com/browse.php?id=3,我希望它将$ id设置为3并显示相关产品。但是,尽管设置了$ id,它仍然默认为0。我的代码中显然有不正确的地方吗?解析方案

希望PHP使用$ _POST和$ _GET作为全局变量。 PHP过去一直是以这种方式设置的,但是新版本需要你明确引用这些变量。



你可以试试这个:

  setdefault($ _ GET ['id'],0); 

函数setdefault(& $ var,$ default =)
{
if(!isset($ var))
{
$ var = $ default;






甚至更简单(使用三元运算符):

  $ id = array_key_exists('id',$ _GET)? $ _GET ['id']:0; 


I'm fairly new to PHP and am creating a website for my company. I am using some existing code that I have obtained but can't seem to make it work properly - any help would be much appreciated!

I have a variable, $id, which identifies the product category type to display on the page. I first need to check that the id variable has been set and if not, default the variable to category 0.

The code I have is as follows:

setdefault($id, 0);

function setdefault(&$var, $default="") 
{
   if (!isset($var)) 
   {
      $var = $default;
   }
}

So with the address www.website.com/browse.php, I would expect it to default to $id=0; with the address www.website.com/browse.php?id=3, I would expect it to set $id to 3 and display the relevant products. However, despite setting $id, it still defaults to 0. Is there something obviously incorrect with my code?

解决方案

You are probably expecting PHP to use the $_POST and $_GET as global variables. PHP used to be setup this way, back in the day, but newer versions require you to explicitly reference these variables.

You could try this:

setdefault($_GET['id'], 0);

function setdefault(&$var, $default="") 
{
   if (!isset($var)) 
   {
      $var = $default;
   }
}

or even more simply (using the ternary operator):

$id = array_key_exists('id', $_GET) ? $_GET['id'] : 0;

这篇关于PHP / HTML - isset函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆