Jump to content

PHP Loops


jadelantern

Recommended Posts

Hi guys

 

I just wanted to make a short post and talk about an issue im having and maybe get some advice. I know that loops aren't that hard to grasp and I shouldn't be having this much trouble understanding them but im just not getting it. I dont really know how to explain it but loops (like looping through mysql in an update statement) is foren to me and i was wondering if anyone had any advice for maybe learning them or maybe something im just over looking or maybe some good tutorials.

I really want to get them down and start using them in scripts i right but im getting so frustrated because i constantly hear how easy they are and im just not getting it.

if i wasn't clear please let me know and ill try to explain more clearly

thanks guys

JL

Link to comment
Share on other sites

You can look over any functions or examples at the php.net site

 

If you do a mysql query and the results is an array, using the while statement is similar to doing a foreach loop of an array

 

What you want to do with the results afterwards depends what you need done, do another query and do an update,insert,delete,etc...

 

You can for example use an if/else and depending if something meets a condition do the appropriate mysql query needed.

Edited by QuickOldCar
  • Like 1
Link to comment
Share on other sites

What is it that you don't understand? You say you have a problem with loops, but what is it?

Hi and thank you for replying.

 

I am a Designer for a software company (I know you must be thinking how the heck I did that and not understand loops) and I get some things that actually aren't that difficult but because I don't understand loops im having a HARD time getting things that need loops done. My problem with loops is very frustrating because I understand a LOT of things that are supposed to be harder to grasp like arrays, querying mysql from PHP, retrieving the data and have it populate a table etc.  I can do and understand "simple" for loops for example:

 

<?php
for($i=0;$i<10;$i++){
echo $i;
}
?>
 
I can do stuff like that till the cows come home, but let say i'm handed a spreadsheet full of users and their address, im told the 200 users on that spreadsheet have the correct address and last name and but the address/last name in the mysql user table are wrong so I need to update those user from the spreadsheet.  I don't have an issue with connecting to the database and all that, I know how open the .csv and store the address and lastname in variables but this gets to the part where I run into my issues with loops.  I have no idea how to setup the for loop to actually loop through the table to find the users and then update their information (this is just a hypothetical scenario); I have to do similar things to this and have struggled with loops.
 
I hope this is a lot more clear and explains what I mean, this is also my 1st and 2nd post so I hope im asking in the right place.
 
thanks guys
 
JL
Link to comment
Share on other sites

In the scenerio you described, would have to have something correct as in the user id or autoincrement id, something unique.

 

Lets say you had their correct id's

pull in csv to a php script

foreach the lines as data array

using whatever delimiter you use in csv explode the data

now you have something like $data[0],$data[1] and so on, each of those you will have to know what field they belong to

 

(mysql part)

we are already in a loop of csv data

make the mysql connection before the loop

explode each line by whatever delimiter are using

perform an update using whichever exploded values need

 

so lets just do a simple example

<?php
$my_file = "clients.csv";
if (file_exists($my_file)) {

$con=mysqli_connect("localhost","username","password","databasename");

if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
 
$data = file($my_file);
foreach ($data as $line) {
$line = trim($line);
$exploded = explode("|",$line);//using pipe as delimiter
 
$id = mysqli_real_escape_string($con, $exploded['0']);
$firstname = mysqli_real_escape_string($con, $exploded['1']);
$lastname = mysqli_real_escape_string($con, $exploded['2']);
 
mysqli_query($con,"UPDATE ClientsTable SET Lastname='$lastname'
WHERE id='$id'");

}
 
mysqli_close($con);
}
?>
Edited by QuickOldCar
  • Like 1
Link to comment
Share on other sites

 

In the scenerio you described, would have to have something correct as in the user id or autoincrement id, something unique.

 

Lets say you had their correct id's

pull in csv to a php script

foreach the lines as data array

using whatever delimiter you use in csv explode the data

now you have something like $data[0],$data[1] and so on, each of those you will have to know what field they belong to

 

(mysql part)

we are already in a loop of csv data

make the mysql connection before the loop

explode each line by whatever delimiter are using

perform an update using whichever exploded values need

 

so lets just do a simple example

<?php
$my_file = "clients.csv";
if (file_exists($my_file)) {

$con=mysqli_connect("localhost","username","password","databasename");

if (mysqli_connect_errno()) {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
 
$data = file($my_file);
foreach ($data as $line) {
$line = trim($line);
$exploded = explode("|",$line);//using pipe as delimiter
 
$id = mysqli_real_escape_string($con, $exploded['0']);
$firstname = mysqli_real_escape_string($con, $exploded['1']);
$lastname = mysqli_real_escape_string($con, $exploded['2']);
 
mysqli_query($con,"UPDATE ClientsTable SET Lastname='$lastname'
WHERE id='$id'");

}
 
mysqli_close($con);
}
?>

ugh... is it really this simple?

 

this makes me want to bang my head against the wall.

 

Thank you for the help QuickOldCar

 

JL

Link to comment
Share on other sites

 . . . let say i'm handed a spreadsheet full of users and their address, im told the 200 users on that spreadsheet have the correct address and last name and but the address/last name in the mysql user table are wrong so I need to update those user from the spreadsheet.  I don't have an issue with connecting to the database and all that, I know how open the .csv and store the address and lastname in variables but this gets to the part where I run into my issues with loops.  I have no idea how to setup the for loop to actually loop through the table to find the users and then update their information (this is just a hypothetical scenario); I have to do similar things to this and have struggled with loops.

 

Then I don't think your issue is with loops. In this situation, just assume you have ONE record to compare and update in the database. Create that process. Then create a loop to get one record at a time and perform the same process. If you can do it once, you can do it many times.

  • Like 2
Link to comment
Share on other sites

Yeah, it's not a problem with loops per se, but rather an issue with your approach to problem solving in general.  You need to break the problem down into individual chunks, like:

 

Can you obtain a single record that needs to be updated?

Can you update that record?

Can you expand that process to two records?  Howabout three or more?

 

Most problems are actually a collection of many smaller problems.  If you can solve those, then you should be able to put it all together.

 

That said, I recommend you do further research on arrays and loops.  Regular for-loops aren't used much in PHP.  Instead, foreach takes its place in most cases, and while-loops tend to handle everything else.  It's not that you can't use a normal for-loop, it's just not nearly as common.  The reason being that this:

$arr = array(1, 2, 3, 4);
 
for ($i = 0; $i < count($arr); ++$i) {
    echo $arr[$i] + 1 . '<br />';
}

is the same as:

$arr = array(1, 2, 3, 4);
 
foreach ($arr as $num) {
    echo $num + 1 . '<br />;
}

but, as you can see, the second one is easier to read and write.

  • Like 1
Link to comment
Share on other sites

but, as you can see, the second one is easier to read and write.

 

I would go further than just stating using foreach() on an array is easier to read and write. I think it is downright wrong in 99% of cases. It assumes that the indexes of the array are numerically based and sequential. While that may be the case when you know the source of the array when writing the code, you don't know if the array format may be changed in the future such that the process would fail. A foreach() loop is much more fool-proof and resilient if the intent is to iterate through the values of an array.

 

I've also been seeing a lot of instances on the forum where people are getting a count of the results from a DB query and then using that count to run the loop to get the records - either in a while()or a foreach(). While that is slightly less problematic since the count of records will not change I would also consider it wrong. A while() loop using the ability to get the next record is the right way

 

while($row = mysqli_fetch_assoc($con, $result)) {}

 

I've never seen it, but an error could occur when getting a record from the result set. Using a while() loop in that manner ensures that the page doesn't fail with an unhanded exception.

Link to comment
Share on other sites

Hey guys another question about loops

 

I would love to become strong with them and turn this weakness into a strength, what is the best way to make myself more familiar with loops? I was thinking maybe just try tutorials over and over until something clicked but I don't know if thats the best way and the only tutorials I find are FAR too easy or are on a beginner level.  Although I am not where I want to be with loops I am a step above beginner level.

 

thanks guys!

 

JL

Link to comment
Share on other sites

read a book on programming. Every language (almost) has loops, whether they use verbs like 'for', 'foreach' 'do -while', 'repeat - until' or whatever else I've forgotten. There's nothing magical. You have a block of code that you want to run over and over against some kind of data and the loop does it for you. It's just a matter of choosing the right loop for your situation. Some loops check the condition prior to executing the included code, others check it at the end.

 

This is not rocket science so you simply need to spend some time reading and learning instead of crying.

Link to comment
Share on other sites

Yup, basically loops themselves have two parts:

 

1. The block of code that will be repeated

2. Some sort of condition to tell the loop to keep looping

 

That's it.  The big three are while, for, and do-while.

 

While loops:

while (/* some condition is true */) {
    // do stuff
}

The while checks the condition first.  If it's true, it executes the block of code.  If it's not true, it does not execute the block of code.  That means you're not guaranteed that anything in the loop will actually execute.

 

Do-while loops:

do {
    // stuff
} while (/* some condition is true */)

This one isn't used very often.  It's 99% the same as a regular while-loop except the part in the do block will be executed before the condition is checked.  So, you're guaranteed at least one pass through the code.

 

For loops:

for (/* initialization */; /* some condition is true */; /* end-of-iteration statement */ ) {
    // do stuff
}

For-loops are the most complex, but they're still not hard.  It can be translated into:

/* initialization */
 
while (/* some condition is true */) {
    // do stuff
    /* end-of-iteration statement */
}

So, with a concrete example:

for ($i = 0; $i < 10; ++$i) {
    echo $i . '<br />';
}
 
// is the same as:
 
$i = 0;
 
while ($i < 10) {
    echo $i . '<br />';
    ++$i;
}

In PHP (and other languages), there's also foreach, which is special.  It uses an internal structure called an iterator to go through a collection (usually an array) one element at a time.  So, it always starts at the first element and ends at the last element, unless you do something like use break to end the loop prematurely.  You've seen them before, I'm sure:

$arr = array(1, '6' => 'monkey butt', 'Mississippi', 'orange' => 'is the new black');
 
foreach ($arr as $item) {
    echo $item . '<br />';
}

So, yeah, that's it.  Loops are not hard.  You just need to practice them.  Make a few test scripts and see how they work.  Chances are, like I said before, you're freaking out because you're not breaking your problems down into manageable parts.

Link to comment
Share on other sites

Regarding your first paragraph, are you saying a foreach is wrong 99% of the time, or a for-loop?  It reads as a for-loop can break if you're not dealing with numeric keys, but I want to double check.

 

Yeah, I see that could cause confusion. That first paragraph was in reference to using a for() loop with an incrementing variable to loop through the array values is "wrong" in almost all cases (there are a few cases where it makes sense). It assumes the array is numerically indexed with sequential numbers. A foreach() loop guarantees you will iterate through all the values in the array.

  • Like 1
Link to comment
Share on other sites

  • 4 weeks later...

what sort of issues? we can only help with specific questions.

 

loops are a conditional statement, like an if(some_condition_being_tested){ ... }, except instead of running just one time when the condition being evaluated is true, they LOOP as long as the condition being evaluated is true.

Link to comment
Share on other sites

To be honest I almost feel silly talking about this because other programmers I speak to all tell me that loops are just dirt easy and I "should not" be having any issue with them but honestly im about ready to pull my hair out.  I understand array's no problem but loops always throw me.

 

Ive looked at tutorial sites on loops but the loops are too basic and easy, i need something that's deeper with harder loop examples that I can get into; Does anyone have any idea where i can find some?

Link to comment
Share on other sites

If you are having this much trouble with loops - with repetition being one of THE BASIC CONCEPTS OF COMPUTING - you may be in the wrong hobby/class/business.  Really?  You can't find a tutorial that explains the usage of whatever loop command you are trying to use?  Really?  You've read the php manual on FOR, WHILE, FOREACH and still don't get it?

 

Either you are not trying, or you will run into lots more difficulties with programming as you reach farther into it.  I'm sad for you :(

 

One last attempt.

 

Data is stored in groups such as arrays, lists, table records, etc.  One grabs this data with some command and then tries to use all of it ONE piece at a time.  That means you have to imagine being at your desk with a stack of paper in front of you with each paper having one piece of info on it.  Your boss says go thru all this and do xyz with each piece of paper's info.  So - what do you do?  You pick up the first piece of paper (data) and then do all the parts of the xyz task your boss wants done.  Then you do the whole process again - grab a paper, do the xyz stuff and repeat.  That is a human loop, otherwise known as menial or clerical labor.  Computers are great at this!  They use the loop construct (For, While, Foreach) to do the exact same thing. 

 

A simple loop to process the 50 pages that the boss gave you:

 

 

while ($page = mysqli_fetch_array($query_results)
{ 
   // call a function to do something with the current page of data
      Do_XYZ($page);
}

 

The while loop in this case is processing the results of a query that produced (let's say) 50 records of data.  The while loop will give you one of those records each time it loops and while you have that one record your code inside the loop does things with it.  In this case that is a call to a function called Do_XYZ which is also passed the $page variable which contains the data to be worked on that time.  When the query results run out that will end the loop because when the mysqli_fetch_array command has no more results it will return false which the while loop will evaluate as false and quit.  (When the fetch DOES return a row into the $page variable that is interpreted by While as True.)

 

It doesn't get any easier than this.   

Link to comment
Share on other sites

 Jadelantern,

 

Can I ask what your background is?  Have you finished school yet?  Have you programmed in some lower level languages which don't treat loops the same way as higher ones do and perhaps you just don't recognize them now?  How long have you been programming and have you ever completed a project? (It had to have a loop in it somewhere!)

 

If my previous post doesn't make sense to you in some way as to shed some feeling of understanding, I'm afraid you really must consider some other endeavor.  :(

Link to comment
Share on other sites

I think your issue is with how you approach problem solving in general. If your previous posts are any indication, you're one of those people who sees an entire forest but can't focus on an individual tree. So, it's not the loops that are the root of your issue, but rather that you think you need to solve whatever problem you have with just a loop. That there's some magic combination of statements in a loop that will solve everything, and you're beating yourself up for not seeing it.

 

That's not how programming is actually done.

 

Break your problem into parts. Solve each manageable piece, then combine them. Over time you'll be able to skip steps, just like in math. Patterns will emerge, and your own experience will inform you of the route to take because you've done it before. That's why 'everyone else' seems to create these things seemingly from thin air. You're not there yet, and you shouldn't expect to be. You need to take baby steps and, again, solve your problem by chopping it up and attacking those individual pieces.

 

EDIT: Here's a test -

 

Given the following array:

 

$array = array(1, 2, 3, 4, 5);
Write some code that will go through the array and echo whether the value is even or odd. How you approach this will inform me whether or not I'm right about how you approach problems. Edited by KevinM1
Link to comment
Share on other sites

If you are having this much trouble with loops - with repetition being one of THE BASIC CONCEPTS OF COMPUTING - you may be in the wrong hobby/class/business.  Really?  You can't find a tutorial that explains the usage of whatever loop command you are trying to use?  Really?  You've read the php manual on FOR, WHILE, FOREACH and still don't get it?

 

Either you are not trying, or you will run into lots more difficulties with programming as you reach farther into it.  I'm sad for you :(

 

One last attempt.

 

Data is stored in groups such as arrays, lists, table records, etc.  One grabs this data with some command and then tries to use all of it ONE piece at a time.  That means you have to imagine being at your desk with a stack of paper in front of you with each paper having one piece of info on it.  Your boss says go thru all this and do xyz with each piece of paper's info.  So - what do you do?  You pick up the first piece of paper (data) and then do all the parts of the xyz task your boss wants done.  Then you do the whole process again - grab a paper, do the xyz stuff and repeat.  That is a human loop, otherwise known as menial or clerical labor.  Computers are great at this!  They use the loop construct (For, While, Foreach) to do the exact same thing. 

 

A simple loop to process the 50 pages that the boss gave you:

while ($page = mysqli_fetch_array($query_results)
{ 
   // call a function to do something with the current page of data
      Do_XYZ($page);
}

The while loop in this case is processing the results of a query that produced (let's say) 50 records of data.  The while loop will give you one of those records each time it loops and while you have that one record your code inside the loop does things with it.  In this case that is a call to a function called Do_XYZ which is also passed the $page variable which contains the data to be worked on that time.  When the query results run out that will end the loop because when the mysqli_fetch_array command has no more results it will return false which the while loop will evaluate as false and quit.  (When the fetch DOES return a row into the $page variable that is interpreted by While as True.)

 

It doesn't get any easier than this.   

 

Well thanks for the kick in the head mate but i don't need anymore of those as ive managed to do that just find by myself; Also I don't believe im in the the wrong field as ive written hundreds of pages of code   in PHP, Java, Javascript unix/linux etc. As ive stated before I have no problems with Array's, entering/retrieving data from SQL/MYSQL databases, ive set up trouble shot and optimized dozens of databases and with my degree in Computer Science I do "Thank you" for replying to my post but  but I do believe im in the correct career field and you have no need to feel sorry for me.  Also please read where I said i understand simple loops and can do those with "NO" problem and the issue with tutorials i've found is  they teach "simple" loops and are too easy thats why i asked if anyone knew a site where i can/could find more advanced tutorials. 

 

Because I feel I might not be coming across correctly let me give an example of what I mean, a few years back(maybe 5 - 6 years ago) I bought a chess program that had 10 levels from basically a monkey to a master player.  For some odd reason I just couldn't ever beat level 4 (it was a level described as a decent player with decent mid-game skills and knight play but poor pawn movement). I skipped this level to just try some of the other level's out and realized I was able to beat level's 5 and 6 without much issue and off/on could beat 7 but I was never able to beat lv 4.

 

Although I will say responses like yours are the reason I hate asking things on a public form and i wish i would have just P.M.'ed a Mod or another member to ask the question because I dont need to be spoken to like im an idiot or have anyone pity me; Ive seen/heard a lot of people say they have issues with Arrays and that seems unusual to me because I picked up array's right Array (hehe right Array) and didn't have any problem with them at all. matter of fact at first I thought "this is too easy I must be missing something" and kept reviewing them because others were having so many issues with them. So when i see people that do have an issue with Array's I always figure it might take them just a little more time to turn the corner.

 

So thanks for your reply and don't feel sorry for me mate I just need a leg up to turn this corner and finally beat level 4.

 

Thanks

 

JL

Link to comment
Share on other sites

I think your issue is with how you approach problem solving in general. If your previous posts are any indication, you're one of those people who sees an entire forest but can't focus on an individual tree. So, it's not the loops that are the root of your issue, but rather that you think you need to solve whatever problem you have with just a loop. That there's some magic combination of statements in a loop that will solve everything, and you're beating yourself up for not seeing it.

 

That's not how programming is actually done.

 

Break your problem into parts. Solve each manageable piece, then combine them. Over time you'll be able to skip steps, just like in math. Patterns will emerge, and your own experience will inform you of the route to take because you've done it before. That's why 'everyone else' seems to create these things seemingly from thin air. You're not there yet, and you shouldn't expect to be. You need to take baby steps and, again, solve your problem by chopping it up and attacking those individual pieces.

 

EDIT: Here's a test -

 

Given the following array:

 

$array = array(1, 2, 3, 4, 5);
Write some code that will go through the array and echo whether the value is even or odd. How you approach this will inform me whether or not I'm right about how you approach problems.

 

I think you are correct I "KNOW" there is something im missing i just need to find that last piece to the puzzle.  Im walking out the door right now to get my car inspected and i will post the reply to this once I get home.

 

thank you

 

JL

Link to comment
Share on other sites

Whatever do you mean by "simple loops" and that you need 'more advanced tutorials'???  LOOPS ARE SIMPLE!  That's all there is.  As KevnM says perhaps your 'problem' is not the loop but the code inside that gets executed upon each iteration.

 

All a loop does is repeat a set of code for you.  As KM says, break down your task into ONE execution of the code you have and make it work on ONE set of data until you're happy.  Now wrap it in a looping construct and you have it.  That's all there is.

 

I find it impossible to believe that you have written any kind of code from start to finish that did not involve a loop of some kind.  I also worry about the state of college level teaching of CSI if you could get a degree without understanding this concept.

 

I apologize (kind of) if you found my last post too much to handle, but I think we all agree that your inability to pick this up from all the help that has been provided is mind-boggling and I let myself go into frustration mode.  And - you don't have to quote back to me my entire post (as the rules state) when you have an issue or question about it.  Really - we can all read it in its original spot.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.