473,323 Members | 1,570 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,323 software developers and data experts.

Array and Loop problems.

Heya guys.

I have the code

Expand|Select|Wrap|Line Numbers
  1. $arr = array($s0, $s1, $s2, $s3, $s4, $s5, $s6, $s7, $s8, $s9);
  2.  
  3. for ($title=0; $title<=$arr; $title++) { echo "
  4.                    <tr>
  5.                       <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>
  6.                </tr>"; }  
  7.  
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
Feb 13 '10 #1

✓ answered by Atli

Ok.

I would try to create an array of data that looks something like this:
Expand|Select|Wrap|Line Numbers
  1. $sections = array(
  2.     array(
  3.         'title' => 'First section',
  4.         'subsections' => 2
  5.     ),
  6.     array(
  7.         'title' => 'Second section',
  8.         'subsections' => 1
  9.     ),
  10.     array(
  11.         'title' => 'Third section',
  12.         'subsections' => 3
  13.     ),
  14. );
(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:
Expand|Select|Wrap|Line Numbers
  1. foreach($sections as $_topIndex => $_section)
  2. {
  3.     echo "{$_topIndex}: {$_section['title']}\n";
  4.     for($subIndex = 0; $subIndex < $_section['subsections']; ++$subIndex)
  5.     {
  6.         echo "   - {$_topIndex}x{$subIndex}\n";
  7.     }
  8. }
This builds text output that looks like:
Expand|Select|Wrap|Line Numbers
  1. 0: First top section
  2.    - 0x0
  3.    - 0x1
  4. 1: Second top section
  5.    - 1x0
  6. 2: Third top section
  7.    - 2x0
  8.    - 2x1
  9.    - 2x2
Which could easily be made to output your HTML tables instead.

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

13 2312
Atli
5,058 Expert 4TB
Hey.

The problem is in the condition for the loop:
Expand|Select|Wrap|Line Numbers
  1. $title<=$arr;
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())
Expand|Select|Wrap|Line Numbers
  1. $title <= count($arr);
Feb 13 '10 #2
Hey thanks for the quick reply.

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

Expand|Select|Wrap|Line Numbers
  1. $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
Feb 13 '10 #3
Hi, I am not sure is this what you want but have a try:

Expand|Select|Wrap|Line Numbers
  1. //declare your array here
  2.  
  3. for($i=0; $i<$count($title); $i++){
  4.     /// Some code
  5.     $i = $i - $arr[i];
  6. }
Feb 13 '10 #4
Atli
5,058 Expert 4TB
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:
Expand|Select|Wrap|Line Numbers
  1. foreach ($limits as $limit) 
  2. {
  3.     for ($i = 0; $i < $limit; ++$i) 
  4.     {
  5.         // Do stuff
  6.     }
  7. }
Feb 13 '10 #5
Atli
5,058 Expert 4TB
@HellRider
Hey HellRider.

Your code - overlooking the syntax errors - would create an indefinite loop.
Let me explain:
Expand|Select|Wrap|Line Numbers
  1. <?php
  2. // It $title has any elements, the loop is started.
  3. // $i is assigned 0 and it executes the block...
  4. for($i=0; $i<count($title); $i++)
  5. {
  6.     // If $arr[$i] has a positive value (which is fair
  7.     // to assume, given that it is meant to be a limit)
  8.     // then $i will become negative. And being negative
  9.     // the condition of the loop will always evaluate true,
  10.     // the value of $i will decrease each loop, making it run
  11.     // indefinitely.
  12.     $i = $i - $arr[$i];
  13. }
  14. ?>
Feb 13 '10 #6
Hi again.

I'm trying to go by this method now.

Expand|Select|Wrap|Line Numbers
  1. $arr = array($s0, $s1, $s2, $s3, $s4, $s5, $s6, $s7, $s8, $s9);
  2.  
  3. foreach ($arr as $limit) {
  4.  
  5.   for ($subs = 0; $subs <= $limit; $subs++)
  6.  
  7.            { echo " 
  8.  <tr>
  9.       <td class='post_form_text3' style='margin-left:10px;'> &nbsp; </td>
  10.   <tr>
  11.       <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>
  12.       </td>
  13.   </tr>
  14.         "; } 
  15.     }
  16.  
  17.  
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.
Feb 13 '10 #7
Atli
5,058 Expert 4TB
What exactly is the data you are working with?
Try doing this on line #2 of that code, and post the result here:
Expand|Select|Wrap|Line Numbers
  1. echo "<pre>", print_r($arr, true), "</pre>"; exit;
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).
Feb 13 '10 #8
What I'm basically trying to do is to loop the 'sub-section' fields seen in the image here.

http://img.photobucket.com/albums/v4.../misc/loop.jpg

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:
Expand|Select|Wrap|Line Numbers
  1. $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.
Feb 14 '10 #9
Atli
5,058 Expert 4TB
Ok.

I would try to create an array of data that looks something like this:
Expand|Select|Wrap|Line Numbers
  1. $sections = array(
  2.     array(
  3.         'title' => 'First section',
  4.         'subsections' => 2
  5.     ),
  6.     array(
  7.         'title' => 'Second section',
  8.         'subsections' => 1
  9.     ),
  10.     array(
  11.         'title' => 'Third section',
  12.         'subsections' => 3
  13.     ),
  14. );
(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:
Expand|Select|Wrap|Line Numbers
  1. foreach($sections as $_topIndex => $_section)
  2. {
  3.     echo "{$_topIndex}: {$_section['title']}\n";
  4.     for($subIndex = 0; $subIndex < $_section['subsections']; ++$subIndex)
  5.     {
  6.         echo "   - {$_topIndex}x{$subIndex}\n";
  7.     }
  8. }
This builds text output that looks like:
Expand|Select|Wrap|Line Numbers
  1. 0: First top section
  2.    - 0x0
  3.    - 0x1
  4. 1: Second top section
  5.    - 1x0
  6. 2: Third top section
  7.    - 2x0
  8.    - 2x1
  9.    - 2x2
Which could easily be made to output your HTML tables instead.

It's the simplest way I can think of to do this.
Feb 14 '10 #10
Wonderful solution, it does indeed work!

I thank you for the help and have a nice day.
Feb 14 '10 #11
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"] ?
Feb 15 '10 #12
Atli
5,058 Expert 4TB
@PHPstarter
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.
Expand|Select|Wrap|Line Numbers
  1. $_POST["title{$titleIndex}sub{$subInded}"];
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:
Expand|Select|Wrap|Line Numbers
  1. <form action="test.php" method="post">
  2. <?php
  3.     for($x = 0; $x < 2; ++$x)
  4.     {
  5.         for($y = 0; $y < 2; ++$y)
  6.         {
  7.             echo "\t<input type=\"text\" name=\"data[{$x}][{$y}]\" value=\"Field {$x}x{$y}\"><br>\n";
  8.         }
  9.         echo "\t<hr>\n";
  10.     }
  11. ?>
  12.     <input type="submit">
  13. </form>
Would generate this HTML:
Expand|Select|Wrap|Line Numbers
  1. <form action="test.php" method="post">
  2.     <input type="text" name="data[0][0]" value="Field 0x0"><br>
  3.     <input type="text" name="data[0][1]" value="Field 0x1"><br>
  4.     <hr>
  5.     <input type="text" name="data[1][0]" value="Field 1x0"><br>
  6.     <input type="text" name="data[1][1]" value="Field 1x1"><br>
  7.     <hr>
  8.     <input type="submit">
  9. </form>
  10.  
Once submitted to test.php, a print_r($_POST) call would produce this:
Expand|Select|Wrap|Line Numbers
  1. Array
  2. (
  3.     [data] => Array
  4.     (
  5.         [0] => Array
  6.         (
  7.             [0] => Field 0x0
  8.             [1] => Field 0x1
  9.         )
  10.  
  11.         [1] => Array
  12.         (
  13.             [0] => Field 1x0
  14.             [1] => Field 1x1
  15.         )
  16.  
  17.     )
  18.  
  19. )
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?
Feb 15 '10 #13
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?
Feb 16 '10 #14

Sign in to post your reply or Sign up for a free account.

Similar topics

1
by: aemazing | last post by:
i've been tryin to do the following - -Add a new flight number to the end of the queue (got it done) -LAnd the plane at the front of the queue - problems wit it- -display the queue - got it done...
4
by: Simon Schaap | last post by:
Hello, I have encountered a strange problem and I hope you can help me to understand it. What I want to do is to pass an array of chars to a function that will split it up (on every location where...
32
by: Carson | last post by:
Hi , Is there a very efficient way to set a double array to 0 ? (I have tried memset, but the result doesn't look correct.) Carson
3
by: Faustino Dina | last post by:
Hi, The following code is from an article published in Informit.com at http://www.informit.com/guides/content.asp?g=dotnet&seqNum=142. The problem is the author says it is not a good idea to...
29
by: yourmycaffiene | last post by:
Okay, this if my first post so go easy on me plus I've only been using C for a couple of weeks. I'm working on a program currently that requires me to read data from a .dat file into a 2d array and...
23
by: sandy | last post by:
I need (okay, I want) to make a dynamic array of my class 'Directory', within my class Directory (Can you already smell disaster?) Each Directory can have subdirectories so I thought to put these...
8
by: per9000 | last post by:
Hi all, I have a two-dimensional array of data, f.x int's. We can imagine that the array is "really large". Now I want the data in it and store this in a one-dimensional array. The obvious...
10
by: SM | last post by:
Hello I'm trying to create a multi dimensional array in JavaScript, but after some reading i still can't figure out how to apply it to my model. Here it is: I have a list A and for each item...
11
by: AZRebelCowgirl73 | last post by:
here is the instructiions I am to use Ask the user to input the number of effective cars in the shop (this number should be between 1 and 100, inclusively). In a loop, controlled by the inputted...
15
by: Steve | last post by:
I am having problems getting values out of an array. The array is set as a global array and values are pushed into it as they are read from a JSON file using a "for loop". When the "for loop" is...
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.