Php array with while loop

PHP Loops (while, do while, foreach & for) Tutorial

In this tutorial, we learn how to control the flow of our application even further. We learn how PHP can help us iterate through sections of code with while, do-while, for and foreach loop statements.

We also cover so called nested loops, which are loops inside other loops. And finally, we compare each loop and explain when to use which one.

By default, the flow of an application written in PHP is sequential. It starts at the top and flows sequentially to the bottom. Many times we will need to alter this flow and allow specific sections of code to be repeated multiple times.

For this purpose, PHP offers us various types of iteration, or looping, logic which are capable of repeating sections of code. Iteration helps us with repetitive tasks and when dealing with big data.

As an example, let’s consider a database for a mailing list which contains entries for a name and email address.

When we want to send an email to everyone on the list, we will need to iterate through all the users in the database one by one. We then fetch their email address and send them an email.

  The interpreter will start at the first user and send an email to that user. If there are more users in the database, it will process the next user in the database and send them an email too.

This process loops over and over for all the users in the database, or until we tell it to stop.

PHP offers us four types of loop statements:

A while loop will tell the interpreter to execute its code block repeatedly, as long as the while expression remains true. The expression will be evaluated each time at the beginning of the loop’s iteration.

The basic form of a while loop is as follows.

Источник

PHP Loops

In this tutorial you will learn how to repeat a series of actions using loops in PHP.

Different Types of Loops in PHP

Loops are used to execute the same block of code again and again, as long as a certain condition is met. The basic idea behind a loop is to automate the repetitive tasks within a program to save the time and effort. PHP supports four different types of loops.

  • while — loops through a block of code as long as the condition specified evaluates to true.
  • do…while — the block of code executed once and then condition is evaluated. If the condition is true the statement is repeated as long as the specified condition is true.
  • for — loops through a block of code until the counter reaches a specified number.
  • foreach — loops through a block of code for each element in an array.

You will also learn how to loop through the values of array using foreach() loop at the end of this chapter. The foreach() loop work specifically with arrays.

PHP while Loop

The while statement will loops through a block of code as long as the condition specified in the while statement evaluate to true.

The example below define a loop that starts with $i=1 . The loop will continue to run as long as $i is less than or equal to 3. The $i will increase by 1 each time the loop runs:

Example

PHP do…while Loop

The do-while loop is a variant of while loop, which evaluates the condition at the end of each loop iteration. With a do-while loop the block of code executed once, and then the condition is evaluated, if the condition is true, the statement is repeated as long as the specified condition evaluated to is true.

The following example define a loop that starts with $i=1 . It will then increase $i with 1, and print the output. Then the condition is evaluated, and the loop will continue to run as long as $i is less than, or equal to 3.

Example

Difference Between while and do…while Loop

The while loop differs from the do-while loop in one important way — with a while loop, the condition to be evaluated is tested at the beginning of each loop iteration, so if the conditional expression evaluates to false, the loop will never be executed.

With a do-while loop, on the other hand, the loop will always be executed once, even if the conditional expression is false, because the condition is evaluated at the end of the loop iteration rather than the beginning.

PHP for Loop

The for loop repeats a block of code as long as a certain condition is met. It is typically used to execute a block of code for certain number of times.

The parameters of for loop have following meanings:

  • initialization — it is used to initialize the counter variables, and evaluated once unconditionally before the first execution of the body of the loop.
  • condition — in the beginning of each iteration, condition is evaluated. If it evaluates to true , the loop continues and the nested statements are executed. If it evaluates to false , the execution of the loop ends.
  • increment — it updates the loop counter with a new value. It is evaluate at the end of each iteration.

The example below defines a loop that starts with $i=1 . The loop will continued until $i is less than, or equal to 3. The variable $i will increase by 1 each time the loop runs:

Example

PHP foreach Loop

The foreach loop is used to iterate over arrays.

The following example demonstrates a loop that will print the values of the given array:

Example

There is one more syntax of foreach loop, which is extension of the first.

Example

 "Peter Parker", "email" => "peterparker@mail.com", "age" => 18 ); // Loop through superhero array foreach($superhero as $key => $value)< echo $key . " : " . $value . "
"; > ?>

Bootstrap UI Design Templates

Is this website helpful to you? Please give us a like, or share your feedback to help us improve. Connect with us on Facebook and Twitter for the latest updates.

Источник

PHP: How to print associative array using while loop?

try this syntax and this is best efficient way to do your job.

while (list($key, $value) = each($array_expression)) < statement > 1, 'b' => 2, 'c' => 3); print_r($data); while (list($key, $value) = each($data)) < echo '$'.$key .'='.$value; >?> 

For reference please check this link.

Thanks. This is what I’m looking for 🙂 I don’t use while loop much in my projects, only for and foreach loop.

The best and easiest way to loop through an array is using foreach

 foreach ($assocArray as $key => $value) echo $key . ' = ' . $value . '
';
$assocarray = array('a' => 1, 'b' => 2, 'c' => 3); $keys = array_keys($assocarray); rsort($keys); while (!empty($keys)) < $key = array_pop($keys); echo $key . ' = ' . $assocarray[$key] . '
'; >;

I have a simple solution for this, it will get the job done..

$x = array(0=>10,1=>11,2=>"sadsd"); end($x); $ekey = key($x); reset($x ); while(true)< echo "
".key($x)." mt24">
)" data-controller="se-share-sheet" data-se-share-sheet-title="Share a link to this answer" data-se-share-sheet-subtitle="" data-se-share-sheet-post-type="answer" data-se-share-sheet-social="facebook twitter devto" data-se-share-sheet-location="2" data-se-share-sheet-license-url="https%3a%2f%2fcreativecommons.org%2flicenses%2fby-sa%2f4.0%2f" data-se-share-sheet-license-name="CC BY-SA 4.0" data-s-popover-placement="bottom-start">Share
)" title="">Improve this answer
answered Jan 15, 2020 at 8:02
Add a comment |
0

Try code below:

$assocArray = array('a' => 1, 'b' => 2, 'c' => 3); $obj = new ArrayObject($assocArray); foreach ( $obj as $key => $value ) < echo '$' . $key .'='. $value . "
"; >

This question is in a collective: a subcommunity defined by tags with relevant content and experts.

Источник

adding values into an array using a while loop

So what I'm trying to do is create a live friends search. To do this I need an array of names for AJAX to search through. Heres my while loop.

if($_REQUEST['D'] == 'viewfriends') < $FREINDS = array(); $FRIENDS_QUERY = "SELECT * FROM `FRIENDS` WHERE `USER` = 'Username>' AND `STATUS` = 'accepted' ORDER BY `ID` Limit 10 ;"; $FRIENDS_RESULT = mysql_query($FRIENDS_QUERY); if(mysql_num_rows($FRIENDS_RESULT) > 0) < while($FRIENDS_ROW = mysql_fetch_assoc($FRIENDS_RESULT)) < $sql = "SELECT * FROM `USERS` WHERE `USERNAME` = '' ;"; $REQUEST_ROW = mysql_fetch_assoc(mysql_query($sql)); $FRIENDS = $REQUEST_ROW['USERNAME']; > echo json_encode($FRIENDS); > else < echo'
Sorry, You have no friends at this time. sadface.
'; > >

im confused on the injects because its just requesting information from the database. and what do you mean by ancient mysq functions?

4 Answers 4

You can't echo an array. You can use either print_r($friends) to display the whole row of fields requested in the query (you request *) or you can echo $friends['name'] (depending on how you declared name in your database)

if($_REQUEST['D'] == 'viewfriends') < $FRIENDS = array(); $USERNAME = $Modules['User']->Username; $SQL_QUERY = "SELECT F.*, U.* FROM FRIENDS AS F LEFT JOIN USER AS U ON F.USER = U.USERNAME WHERE F.USERNAME = '' AND STATUS = 'accepted' ORDER BY F.ID LIMIT 10"; $RESULTS = mysql_query($SQL_QUERY); if(mysql_num_rows($RESULTS) > 0) < while($ROW = mysql_fetch_assoc($RESULTS)) < $FRIENDS[] = $ROW['USERNAME']; >echo json_encode($FRIENDS); > else < echo'
Sorry, You have no friends at this time. sadface.
'; > >
 $FRIENDS[] = $REQUEST_ROW['USERNAME']; 

then print_r($FRIENDS); echo will output array you need to loop the array or echo json_encode($FRIENDS); to see something

also are you sure that USERNAME is uppercase and not just username in lowercase lowercase as well as for the table name.

also i think you can use a JOIN clause instead of making to SQL requests

yes, i use the same QUERY for other functions. i do all my tables and Columns in sql as UPPERCASE to avoid this :).

$FREINDS = array(); should be $FRIENDS = array(); .

$FRIENDS = $REQUEST_ROW['USERNAME'] should be $FRIENDS[] = $REQUEST_ROW['USERNAME']

echo $FRIENDS; should be echo json_encode( $FRIENDS );

The PHP won't actually echo out an array. If you do an echo of an array, it outputs "Array". Plus your javascript wouldn't know what to do with a PHP array if it did pass it that way.

Also, you should really listen to the feedback in the comments. Your code is very vulnerable to attack and not set up to scale well for such a potentially huge app.

You have a couple of issues that make your code either less secure or less efficient. The most obvious inefficiency is that you are doing a database call inside your while loop, so if someone has 10 friends, that means you've done 11 database queries when you may have only needed one or two. Here are the two queries:

SELECT * FROM `FRIENDS` WHERE `USER` = 'Username>' AND `STATUS` = 'accepted' ORDER BY `ID` Limit 10 SELECT * FROM `USERS` WHERE `USERNAME` = '' 

So before we determine if these two can be combined, the first big red flag is the SELECT * . I use it all of the time, but it will get you kicked out of the better database bars. In your case, it's really unnecessary. We know from the second query that the only thing you are using from the first query is the $FRIENDS_ROW['FRIEND'] to match against the USERNAME . So that first query can become:

SELECT FRIEND FROM `FRIENDS` WHERE `USER` = 'Username>' AND `STATUS` = 'accepted' ORDER BY `ID` Limit 10 

You also have the SELECT * in the second query, and we can tell that (for now) the the only thing you are using is the USERNAME , so it can become:

SELECT USERNAME FROM `USERS` WHERE `USERNAME` = '' 

Finally, we can see from the second query that the FRIEND name and the USERNAME are identical; otherwise why would you query for the usernames where the username equals the friend name. If that's the case, we can drop your second query completely, since we already know the usernames from the first query.

The reason why it's both inefficient and unsafe is because you are using the OG mysql functions, which are clunky and don't offer the option of prepared statements. Prepared statements let you (among other things) put variables in your query in such a way that when you actually call the query, the parts that are variables are known and can thus be sanitized, avoiding the horrors of mysql injections that everyone has mentioned.

I won't bore you with the play-by-play, but here is what your code might look like if you used the newer mysqli library with a prepared statement:

if($_REQUEST['D'] == 'viewfriends') < $friends = array(); $friend_lookup = $mysqli->prepare("SELECT FRIEND FROM FRIENDS WHERE USER = ? AND STATUS = 'accepted' ORDER BY FRIEND"); $friend_lookup -> bind_param('s', $userName); $userName = $Modules['User']->Username; $friend_lookup -> execute(); $friend_lookup -> bind_result($friend); while($friend_lookup -> fetch()) < $friends[] = $friend; >if($friends) < echo json_encode($friends); >else < echo "Sorry, no friends. Boo."; >> 

Источник

Читайте также:  Python ловим все ошибки
Оцените статью