I'm using a script to create additional form rows.
It loops the $i number for certain text fields
When I run this script, the offset is undefined because it doesn't exsist.
I need to use the if(isset()) function, but I am unsure how I would place it in the code.
Can anyone help?
for ($i=0; $i<100; $i++) {
if ($text['length'][$i] == "") $text['length'][$i] = "0";
if ($text['bredth'][$i] == "") $text['bredth'][$i] = "0";
if ($text['height'][$i] == "") $text['height'][$i] = "0";
if ($text['weight'][$i] == "") $text['weight'][$i] = "0.00";
All the lines starting with 'if' show the notice:
Notice: Undefined offset: 1 in C:\xampp\htdocs\newparcelscript.php on line 41
SOLVED
Infact i did not require and 'if' stament at all, because the creation of the rows and the setting of the values are run together.
for ($i=0; $i<100; $i++) {
$text['length'][$i] = "0";
$text['breadth'][$i] = "0";
$text['height'][$i] = "0";
$text['weight'][$i] = "0.00";
I think testing for empty()
is what you're looking for here.
for($i = 0; $i < 100; $i++)
{
if(empty($text['length'][$i]) === TRUE) $text['length'][$i] = 0;
...
...
}
depending on what you're trying to do here, I either suggest you use one of the following isset/empty combinations
if (isset($text['length'][$i]) == false or empty($text['length'][$i]) == true)
if (isset($text['length'][$i]) == true and empty($text['length'][$i]) == true)
The error is most likely coming from testing against a index that doesn't exist: if($text['length'][$i] == "")
For this situation, if you need to insert values for undefined fields, use empty()
.
empty()
returns TRUE if the values is a empty string, while !isset()
will return FALSE.
There are many questions about this, for example look here.
Something like this:
for ($i=0; $i<100; $i++) {
if (empty($text['length'][$i])) $text['length'][$i] = "0";
if (empty($text['bredth'][$i])) $text['bredth'][$i] = "0";
if (empty($text['height'][$i])) $text['height'][$i] = "0";
if (empty($text['weight'][$i])) $text['weight'][$i] = "0.00";
}