Home > Article > Backend Development > How to solve the undefined index prompt in PHP (multiple methods), undefinedindex_PHP tutorial
1. Related information
When you usually use $_post[''] or $_get[''] to get the parameters in the form, Notice: Undefined index: --------;
And we often receive Undefined index errors when receiving data POST from forms
For example: $act=$_POST['action']; Using the above code will always prompt Notice: Undefined index: act in D:testpost.php on line 20. In addition, sometimes Notice: Undefined variable: Submit will appear. ... Wait for some such reminders to appear. These are PHP prompts rather than errors. PHP itself can be used directly without declaring variables in advance, but there will be prompts for undeclared variables. Generally, as a formal website, prompts will be turned off, and even error messages will be turned off.
2. Problem description
That is, PHP will prompt for undeclared variables by default, but we can ignore this default prompt
3. Solution
Method 1: Server configuration modification
Modify the error display mode under the error configuration in php.ini: change error_reporting = E_ALL to error_reporting = E_ALL & ~E_NOTICE
Restart the Apache server after modification to take effect.
Method 2: Initialize variables
That is, after defining a variable, it is specifically initialized, but this cannot determine whether a variable has been initialized due to event-driven
Method 3: Perform isset($_post['']), empty($_post['']) if --else judgment
Method 4: Add @
before the notice code appears@ means there is an error in this line or a warning not to output. For example: @$username=$_post['username']; Add an @ in front of the variable, such as if (@$_GET['action']==' save') { ...
In this way, if a warning occurs in this statement, it will not be output
Method 5: Build a function yourself instead of the value method
The function code is as follows:
function _get($str){ $val = !empty($_GET[$str]) ? $_GET[$str] : null; return $val; }
Then when using it, just use _get('str') instead of $_GET['str'] ~
4. Analysis and Summary
Although PHP provides a good reminder mechanism, it may not be what we want. It is recommended to use method 4 above for processing. This can ensure that the reminder is processed when the reminder is observed, and also retains the reminder mechanism provided by PHP.
The above content is the relevant knowledge shared by the editor on how to solve the undefined index prompt in PHP (multiple methods). I hope it will be helpful to everyone!