How to store values in array in php using while loop

You need to set value properly.

            $movies_id = array();

            while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
                $id = $row['id'];
                $title_id = $row['title_id'];
                    $movies_id[$id] = $title_id; // The proper way
                    //$movies_id[] = [$id => $title_id];
            }

            print_r($movies_id);

The more readable code would be:

            $movies_id = array();

            while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
                    $movies_id[$row['id']] = $row['title_id'];
            }
            print_r($movies_id);

And would result in

array (
    1 => 'Title 1',
    2 => 'Title 2',
    4 => 'Title 4',
    8 => 'Title 8',
)

And key-less soulution would be:

            $movies_id = array();

            while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
                    $movies_id[] = $row['title_id'];
            }
            print_r($movies_id);

And would result in

array (
    0 => 'Title 1',
    1 => 'Title 2',
    2 => 'Title 4',
    3 => 'Title 8',
)

PHP, just like most other programming languages has multiple ways to loop through arrays. The most popular ways to do it usually is with a while, for and foreach operator, but, believe it or not, there are more ways to do it with PHP. In this article, I will walk-through each possibility for reading arrays whilst looping.

1. While Loop

The while loop is probably the most popular because of the recognizable and meaningful name. I always like to think of the while loop as the following.

Whilst something is true, the loop will continue looping or vice versa.

This method is commonly used when working with database results in the style of arrays but at the same time, are a completely feasible way to read non-database result-arrays.

With a plain array, we can create a true or false value depending on if the array has been looped over till the end. To achieve this, another variable must be created, an index indicator variable that does two things, allows us to pick out each of the values in the array as well as instructing the while loop when to stop. It’s somewhat very similar to how a for loop works, which we will touch on later.

PHP Code

        $CodeWallTutorialArray = ["Eggs", "Bacon", "HashBrowns", "Beans", "Bread", "RedSauce"];
        $arrayLength = count($CodeWallTutorialArray);
        
        $i = 0;
        while ($i < $arrayLength)
        {
            echo $CodeWallTutorialArray[$i] ."
"; $i++; }

Output

Eggs
Bacon
HashBrowns
Beans
Bread
RedSauce

2. For Loop

As demonstrated in the last section for while loops, you will see how similar the for loop is. It uses the very same concept for looping and picking out information from the array. Three parameters are needed for the for loop and they are as follows –

  1. An initial counter set to a certain value, usually zero.
  2. A Boolean test, usually involving the initial counter.
  3. A counter increment eg: counter++.

The start of the loop will always look similar to the following –

for ($i = 0; $i < count($arr); $i++)

What’s really important to note here is that you must use semi-colons after the first two parameters otherwise the code will throw an exception. Also, there is no need to increment the counter within the loop, as the for operator does this for you. Let’s put this loop into action in the following PHP.

PHP Code

        $CodeWallTutorialArray = ["Eggs", "Bacon", "HashBrowns", "Beans", "Bread", "RedSauce"];

        for ($i = 0; $i < count($CodeWallTutorialArray); $i++)  {
            echo $CodeWallTutorialArray[$i] ."
"; }

Output

Eggs
Bacon
HashBrowns
Beans
Bread
RedSauce

3. Foreach Loop

This type of loop is my personal favorite way to read arrays, there is no need for a boolean test, just simply pass in the array and do what you want with it. It’s both easy to use, understand and comes in handy for many use-cases. There isn’t a mandatory rule to use a numeric index to pick out data values, the foreach loop essentially rids this concept for you. Let’s see it in action –

PHP Code

       $foodArray = ["Eggs", "Bacon", "HashBrowns", "Beans", "Bread"];

        foreach ($foodArray as $food)  {
            echo $food ."
"; }

Output

Eggs
Bacon
HashBrowns
Beans
Bread

As you can see within the code example, there is much less fluff in terms of code. And, if you name your variables well, the code will make a lot more sense than other looping methods.

4. Do While Loop

You could almost say the do while loop is pretty scarce among PHP code, I personally rarely use it and similarly rarely see it from other peoples code neither. It’s essentially a longer or code-bulkier way of executing a while loop, which in a way, is pretty pointless. At the same time, it’s arguably more readable, but ultimately, it all comes down to preference.

With the do while loop, you will need to create a test within the while operator, just as you would in a pure while loop case.

PHP Code

       $foodArray = ["Eggs", "Bacon", "HashBrowns", "Beans", "Bread"];
        $i = 0;
        
        do {
            echo $foodArray[$i] . "
"; $i++; } while ($i < count($foodArray));

Output

Eggs
Bacon
HashBrowns
Beans
Bread

As you can see in the code, there is a need to create an increment index value that will work part as the test and part to access values from the array.

5. Array Iterator

Now, this is a slightly more advanced method of looping over arrays is called an ArrayIterator. It’s part of a wider class that exposes many accessible variables and functions. You are more likely to see this as part of PHP classes and heavily object-oriented projects. Again with this functionality, you may find it more preferable to others or vice versa. The documentation on this class is well worth eye-balling as you can see exactly what benefits it offers. For example, it instantly exposes a count of the array which is quick and useful.

PHP Code

        $programmingLanguagesArray = ["PHP", "C++", "C#", "Python", "Java"];
        
        $arrObject = new ArrayObject($programmingLanguagesArray);
        $arrayIterator = $arrObject->getIterator();

        while( $arrayIterator->valid() )
        {
            echo $arrayIterator->current() . "
"; $arrayIterator->next(); }

Output

PHP
C++
C#
Python
Java

Function References

Here are the links to the documentation on each of the loops used within this article. Check them out as they are extremely informative and useful for bookmarking for reference later.

  • while
  • for
  • foreach
  • do while
  • ArrayIterator

Summary

With the demonstration of five ways to loop over arrays, you have the luxury of picking a preferred and truly personal way of doing things yourself. In some cases, one will perform better than the other with regards to what you need to achieve. I hope this comes in useful, now go do some cool stuff with some loops! Finally, feel free to copy any of the code in this article to use in your own projects or merely reference.

How can we store value in array using for loop in PHP?

php $a=array('a','b','c'); $c=array(); // for loop for($i=0;$i

How do you add values to an array in a while loop?

Adding values of an array with each other inside a while loop.
The counter stores the number of values contained within the array called numbers..
The sum should contain the sum of all the values from the array..
The first step that i completed, setup the counter variable in place (which works fine):.

Can you use an array in a while loop?

Using while to iterate over an array We can even use while loops to iterate over an array. First we define an array and find out its length, len , using the length property of arrays. Then we define an index variable to iterate over the array .

Can we use for loop for array in PHP?

The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.