Array and Loop problems.

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • PHPstarter
    New Member
    • Jun 2009
    • 77

    Array and Loop problems.

    Heya guys.

    I have the code

    Code:
    $arr = array($s0, $s1, $s2, $s3, $s4, $s5, $s6, $s7, $s8, $s9);
    
    for ($title=0; $title<=$arr; $title++) { echo "
        			   <tr>
        			      <td> &raquo; Sub-section "; echo $subs; echo "."; echo $title; echo ": <textarea class='boe_soi_edit2' cols='38' name='title"; echo $subs; echo "sub"; echo $title; echo "' style='font-size:10pt;float:right;font-weight:normal;'></textarea></td>
    			   </tr>"; }
    So basically, the variables inside the array are passed on from the URL, and they can be anything from 0 to 999 etc, though they most likely won't be higher than 10.

    So, the problem:

    I'm trying to get the loop to echo the code using the value given from the variable as the limiter. Using one variable from the array once..
    First using the value from $s0, then from $s1 etc - u get my drift.

    The issue is that this ends in an infinite loop.
    I've tried foreach also, but no success in obtaining the goal i described here.

    Thanks for answers
  • Atli
    Recognized Expert Expert
    • Nov 2006
    • 5062

    #2
    Hey.

    The problem is in the condition for the loop:
    [code=php]$title<=$arr;[/code]
    There $arr is an array, which when compared like that is just read as TRUE, and when you test whether or not a number is higher or lower than TRUE it always returns TRUE. (Thus, resulting in an indefinite loop.)

    What you want to be doing is comparing the size of the array. To do that you use the count function. (The sizeof function is also available. It is an alias of count())
    [code=php]$title <= count($arr);[/code]

    Comment

    • PHPstarter
      New Member
      • Jun 2009
      • 77

      #3
      Hey thanks for the quick reply.

      Using count() did make it work, but not quite as intended.

      Code:
      $arr = array($s0, $s1, $s2, $s3, $s4, $s5, $s6, $s7, $s8, $s9);
      With this array, let's imagine $s0 = 2, $s1 = 2 and $s3 = 1

      What I tried to make was that the loop would first use $s0 as the limiter, looping the code 2 times, then use $s1 as the limiter and loop the code 2 times - then using $s3 as the limter and looping the code 1 time.

      I don't even know if it is possible, but if it is, I would like to know how =D

      Comment

      • HellRider
        New Member
        • Feb 2010
        • 1

        #4
        Hi, I am not sure is this what you want but have a try:

        Code:
        //declare your array here
        
        for($i=0; $i<$count($title); $i++){
            /// Some code
            $i = $i - $arr[i];
        }

        Comment

        • Atli
          Recognized Expert Expert
          • Nov 2006
          • 5062

          #5
          Ahh ok, I see.

          What you need to do is use two loops, one nested within the other.

          You can use a foreach loop to loop through the values in $arr, and within that loop create a for loop that iterates the number of times specified by the current value from the outer loop.

          Something like:[code=php]foreach ($limits as $limit)
          {
          for ($i = 0; $i < $limit; ++$i)
          {
          // Do stuff
          }
          }[/code]

          Comment

          • Atli
            Recognized Expert Expert
            • Nov 2006
            • 5062

            #6
            Originally posted by HellRider
            Hi, I am not sure is this what you want but have a try:
            Hey HellRider.

            Your code - overlooking the syntax errors - would create an indefinite loop.
            Let me explain:
            [code=php]<?php
            // It $title has any elements, the loop is started.
            // $i is assigned 0 and it executes the block...
            for($i=0; $i<count($title ); $i++)
            {
            // If $arr[$i] has a positive value (which is fair
            // to assume, given that it is meant to be a limit)
            // then $i will become negative. And being negative
            // the condition of the loop will always evaluate true,
            // the value of $i will decrease each loop, making it run
            // indefinitely.
            $i = $i - $arr[$i];
            }
            ?>[/code]

            Comment

            • PHPstarter
              New Member
              • Jun 2009
              • 77

              #7
              Hi again.

              I'm trying to go by this method now.

              Code:
              $arr = array($s0, $s1, $s2, $s3, $s4, $s5, $s6, $s7, $s8, $s9);
              
              foreach ($arr as $limit) {
              
                for ($subs = 0; $subs <= $limit; $subs++)
              
              		   { echo " 
               <tr>
                    <td class='post_form_text3' style='margin-left:10px;'> &nbsp; </td>
                <tr>
                    <td> &raquo; Sub-section "; echo $subs; echo "."; echo $title; echo ": <textarea class='boe_soi_edit2' cols='38' name='title"; echo $subs; echo "sub"; echo $title; echo "' style='font-size:10pt;float:right;font-weight:normal;'></textarea>
                    </td>
                </tr>
              		"; } 
              	}
              It gives me 14 loops, where 14 isn't given anywhere.
              Could be a syntax mistake on my end, but I can't spot it.

              Comment

              • Atli
                Recognized Expert Expert
                • Nov 2006
                • 5062

                #8
                What exactly is the data you are working with?
                Try doing this on line #2 of that code, and post the result here:
                [code=php]echo "<pre>", print_r($arr, true), "</pre>"; exit;[/code]

                P.S.
                There is an error in your HTML markup. The "<tr>" on line #10 of that code shouldn't be there.

                P.P.S.
                In your loop, you use "<=". It should (typically) only be a "=".
                That is, if you are counting indexes (0-9 for 10 items) then you start counting at 0 and use a single "=". - However, if you are counting like a "human" (1-10 for 10 items) then you start at 1 and use a <=. - But you rarely start at 0 and use "<=", because then you are doing an extra loop (11 loops for a limit of 10).

                And note, if you intend to use this to display elements from an array, you are usually going to want to go with indexes (0-9 for 10 items), because array indexes usually start with 0 and end at one less then it's length (0 through 9 for a 10 element array).

                Comment

                • PHPstarter
                  New Member
                  • Jun 2009
                  • 77

                  #9
                  What I'm basically trying to do is to loop the 'sub-section' fields seen in the image here.



                  I'm already looping the longest input fields, which is working fine.
                  They are limited to 9, so only 9 will loop.

                  But it's the sub-section input fields that is the problem.
                  How many times they will loop under each of the big input fields is what the variables are for:
                  Code:
                  $arr = array($s0, $s1, $s2, $s3, $s4, $s5, $s6, $s7, $s8, $s9);
                  Where $s0 is the number of times to loop the sub-section under the first long input field.

                  I already have a working version, but it's not a double loop, and there's a lot of static code.

                  So I tried to make a double loop in order to increase the effectivity, and there began the problem.
                  And the problem is still the same, making the loop use the array variables for each input field.

                  Comment

                  • Atli
                    Recognized Expert Expert
                    • Nov 2006
                    • 5062

                    #10
                    Ok.

                    I would try to create an array of data that looks something like this:
                    [code=php]$sections = array(
                    array(
                    'title' => 'First section',
                    'subsections' => 2
                    ),
                    array(
                    'title' => 'Second section',
                    'subsections' => 1
                    ),
                    array(
                    'title' => 'Third section',
                    'subsections' => 3
                    ),
                    );[/code]
                    (There you could put your $s0-$s9 variables in the 'subsections' elements, if you want.)

                    Then you could build your page using something like this:
                    [code=php]foreach($sectio ns as $_topIndex => $_section)
                    {
                    echo "{$_topInde x}: {$_section['title']}\n";
                    for($subIndex = 0; $subIndex < $_section['subsections']; ++$subIndex)
                    {
                    echo " - {$_topIndex}x{$ subIndex}\n";
                    }
                    }[/code]
                    This builds text output that looks like:
                    [code=text]0: First top section
                    - 0x0
                    - 0x1
                    1: Second top section
                    - 1x0
                    2: Third top section
                    - 2x0
                    - 2x1
                    - 2x2[/code]
                    Which could easily be made to output your HTML tables instead.

                    It's the simplest way I can think of to do this.

                    Comment

                    • PHPstarter
                      New Member
                      • Jun 2009
                      • 77

                      #11
                      Wonderful solution, it does indeed work!

                      I thank you for the help and have a nice day.

                      Comment

                      • PHPstarter
                        New Member
                        • Jun 2009
                        • 77

                        #12
                        Hi again.

                        Continuing from this, I came across a problem I'm not sure how to work around.
                        Considering this script will give me an X number of subsections for the 9 main sections, how can I process the $_POST from this?

                        Each main field is given the name/id= title0, title1, title2 etc.
                        While each subsection is given the name/id= title0sub1 (for title0 subsections), title0sub2, title0sub3 etc.

                        So Im guessing there is an easier way than creating IF codes for all the possible $_POST["title0subX"] ?

                        Comment

                        • Atli
                          Recognized Expert Expert
                          • Nov 2006
                          • 5062

                          #13
                          Originally posted by PHPstarter
                          So Im guessing there is an easier way than creating IF codes for all the possible $_POST["title0subX"] ?
                          Sure. You can just loop through the possible values and dynamically construct the appropriate element name. The element name, after all, is just a string.
                          [code=php]$_POST["title{$titleIn dex}sub{$subInd ed}"];[/code]
                          I recommend using the isset() function to make sure the element exists, though. Otherwise your script is very likely to show undefined index warnings ever now and then.

                          Each main field is given the name/id= title0, title1, title2 etc.
                          While each subsection is given the name/id= title0sub1 (for title0 subsections), title0sub2, title0sub3 etc.
                          There is a better way to do this.

                          Input names, like PHP variables, can be arrays. That is; rather than simulate arrays - like you do in your script - you can have PHP create actual arrays from the input data.

                          For example, this PHP code:
                          [code=html]<form action="test.ph p" method="post">
                          <?php
                          for($x = 0; $x < 2; ++$x)
                          {
                          for($y = 0; $y < 2; ++$y)
                          {
                          echo "\t<input type=\"text\" name=\"data[{$x}][{$y}]\" value=\"Field {$x}x{$y}\"><br >\n";
                          }
                          echo "\t<hr>\n";
                          }
                          ?>
                          <input type="submit">
                          </form>[/code]
                          Would generate this HTML:
                          [code=html]<form action="test.ph p" method="post">
                          <input type="text" name="data[0][0]" value="Field 0x0"><br>
                          <input type="text" name="data[0][1]" value="Field 0x1"><br>
                          <hr>
                          <input type="text" name="data[1][0]" value="Field 1x0"><br>
                          <input type="text" name="data[1][1]" value="Field 1x1"><br>
                          <hr>
                          <input type="submit">
                          </form>
                          [/code]

                          Once submitted to test.php, a print_r($_POST) call would produce this:
                          Code:
                          Array
                          (
                              [data] => Array
                              (
                                  [0] => Array
                                  (
                                      [0] => Field 0x0
                                      [1] => Field 0x1
                                  )
                          
                                  [1] => Array
                                  (
                                      [0] => Field 1x0
                                      [1] => Field 1x1
                                  )
                          
                              )
                          
                          )
                          Which is easy to loop through, in much the same way we did with the $sections array in me earlier post.

                          See what I mean?

                          Comment

                          • PHPstarter
                            New Member
                            • Jun 2009
                            • 77

                            #14
                            I'm sorry but I don't really see how I can get the information into loops in this case.

                            I ran the print_r($_POST) and it printed the array as u posted for me, only without line breaks.

                            Could you please give an example of how I could loop this to use the array data?

                            Comment

                            Working...