473,748 Members | 2,211 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Comparing arrays: foreach or for?

66 New Member
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 5430
pbmods
5,821 Recognized Expert Expert
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
cheesecaker
66 New Member
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
2259
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 a Mysql db.
11
461
by: Peter | last post by:
Hi how can I compare two byte arrays in VB.NET Thank Peter
1
495
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 checking to see if the result has any 1s in it (if so, the arrays are different). This seems to be faster than comparing each bit of the two original arrays one at a time. But I still have to iterate over each element of the array, and I'd like to
18
40005
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 I do
2
1166
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 dragged from a database (I actually have to parse strings to get filenames, but I can already do that). I will be inserting the file names into an
19
3839
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 dictionary keys, based on their content, not their identity. Is this feasible using the arrays directly, or do I need to wrap them in a struct that handles GetHashCode and Equal? If so, is such a wrapper present in the standard class library?
2
7052
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, input box for units of service, description of the service and each row has its own dropdown list of unit fees that apply. Each dynamically created row will return 3 values fee1_choice, fee1_unit and fee1_money. Note The above informaton is...
3
2469
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 the immediate problems I am having first and try to figure the rest out myself. Basically I need to compare the contents of a directory, with the contents of a series of 'csv' files, when those two match it will trigger some moving of the contents of...
110
7026
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 don't. I have gone over a few different examples but they were limited. I was able to find one piece of code that I would like to disect and ask questions about so I can gain a better understanding. $characters = array ( array (...
0
8991
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8831
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9552
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9376
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9326
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9249
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
3315
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2787
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2215
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.