473,383 Members | 1,870 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,383 software developers and data experts.

Comparing arrays: foreach or for?

Okay well, let's say you have a script that evaluates exam questions. Arrays are used for both the answer key and the test taker's provided answers. Repeated comparison is required, so obviously, a loop fits the bill.

I have the following (VERY basic) for loop set up. I'm supplying only a snippet, because the rest doesn't really matter. Two arrays have been filled, one with the answer key, one with the user's answers, with eight array elements (questions) on each array. Each array's starting index is [1].

Expand|Select|Wrap|Line Numbers
  1. for ($i = 1; $i < 8 ; $i++)
  2. {
  3.     if ($answers[$i] == $answerkey[$i])
  4.     {
  5.         $numcorrect++;
  6.     }
  7. }
  8.  
  9. echo $numcorrect;
This correctly outputs the number of correct answers. Now I'm wondering whether I should change this to a foreach loop for some reason, since they're more commonly used with arrays.
Oct 20 '07 #1
2 5409
pbmods
5,821 Expert 4TB
Heya, cheesecaker.

The reason why I am very against using for loops as a method of array traversal in general is because many programmers are tempted to do this:

Expand|Select|Wrap|Line Numbers
  1. for($i=0; $i<sizeof($array); $i++)
  2.  
This is in fact the most inefficient way to traverse an array:
  • sizeof() gets executed at the start of every single iteration, which is a tremendous waste,
  • Any PHP guru can tell you that ++$i is faster than $i++, and
  • for doesn't handle non-numeric indexes without modification, whereas foreach handles them automatically.

Incidentally, a better way to write the above example would be this:
Expand|Select|Wrap|Line Numbers
  1. for( $i = 0; isset($array[$i]); ++$i )
  2.  
Note the use of isset(), which does the same thing but is exponentially faster than using count() or sizeof() at every iteration.

However, in your case, if the size of the array is actually constant, your code will work very nicely (with the exception of you'll want to change $i++ to ++$i). I wouldn't worry about changing it to a foreach.

If you find that there is a large number of questions (without testing, I couldn't tell you exactly how many), you may actually find foreach to be more efficient, as then you only have to look up one symbol instead of two:

Expand|Select|Wrap|Line Numbers
  1. for( $i = 0; isset($array[$i]); ++$i )
  2. {
  3.     echo $array[$i];
  4. }
  5.  
In the above loop, PHP evaluates isset($array[$i]) and echo $array[$i], which means it has to resolve $array and $i, and then find the matching index in $array. That's a lot of symbols to look up.

However, when you use a foreach loop:
Expand|Select|Wrap|Line Numbers
  1. foreach( $array as $element )
  2. {
  3.     echo $element;
  4. }
  5.  
PHP internally creates the variable $element and assigns it the value of each element per iteration, so PHP only has to lookup $element once. It's much more efficient.

For small sets of questions and answers, I wouldn't worry about it. For large sets (probably on the scale of >= 50), consider using foreach instead.
Oct 20 '07 #2
Thanks so much for your detailed post.

I plan to implement a dynamic answer key, as well, so a set number of questions is not going to be the case in the final script.

So could you show me how exactly I would replace the current for loop I have with an efficient foreach loop? Remember, I have to compare each answerkey[] array element with its corresponding answers[] array element.

I'm getting confused because foreach only allows you to bring one array in with the $array as $key => $value syntax. Here I need to compare two arrays. Or would I nest a couple of foreach's? For lets me just bring in as many arrays as I want without any special syntax. Anyway, yeah, I'm quite confused as to this.
Oct 21 '07 #3

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

Similar topics

6
by: Bart Nessux | last post by:
How is this done in php? I've tried several variations of the following: contact_array = ($_POST, $_POST, $_POST, $_POST, $_POST); The ultimate goal is to insert the array into a table in...
11
by: Peter | last post by:
Hi how can I compare two byte arrays in VB.NET Thank Peter
1
by: Iain | last post by:
Hi Hopefully I am missing something really simple with this question, but here goes. I have two Bitarrays that I would like to compare. At the moment, I am XORing one with the other and...
18
by: Mike Bartels | last post by:
Hi Everyone! I have two Arrays A and B. Both arrays are byte arrays with 7 bytes each. The contents of array A and B are the same A = {1, 2, 3, 4, 5, 6, 7}; B = {1, 2, 3, 4, 5, 6, 7}; When...
2
by: David | last post by:
Hi all, How would I go about this? I am doing a document management system and I need to write a clean up routine. I will create two arrays. One of them will have a list of filenames I have...
19
by: Ole Nielsby | last post by:
How does the GetHashCode() of an array object behave? Does it combine the GetHashCode() of its elements, or does it create a sync block for the object? I want to use readonly arrays as...
2
by: assgar | last post by:
Hi Developemnt on win2003 server. Final server will be linux Apache,Mysql and PHP is being used. I use 2 scripts(form and process). The form displays multiple dynamic rows with chechboxs,...
3
by: erbrose | last post by:
Hello all! Newbie here, I've been tasked with a fairly intensive project here and my perl skills are still at a minimum so this post may eventually turn into a long one, but I am only going to ask...
110
by: fjm | last post by:
For some reason, I have always had a hard time understanding arrays as they pertain to php and databases. I understand associative arrays just fine but when there are multidimensional arrays, I kinda...
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...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

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.