1

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";
ecoboff1
  • 11
  • 4

3 Answers3

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] == "")

Scuzzy
  • 12,186
  • 1
  • 46
  • 46
  • Solved, I was creating those rows, but the code for creating and setting values are run simultaneously, so actually i didn't need an 'if' statement at all – ecoboff1 Mar 04 '13 at 23:13
0

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;
    ...
    ...
}
Jordan Doyle
  • 2,976
  • 4
  • 22
  • 38
0

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";
}
Community
  • 1
  • 1
ZolaKt
  • 4,683
  • 8
  • 43
  • 66