user1998735
user1998735

Reputation: 253

using php for loop for arrays

Hi guys I'm kinda new with php and was wondering if anyone can help me with this: Here's my code:

<html>
<body>
<h1>
  <?php
    $movies = array("one","two","three","four");
    $result = count($movies);
    for($f=0; $f <= $result; $f++)
    {
      echo $movies[$f];
    }
  ?>
</h1>
</body>
</html>

What I wanted to do was to display the elements in the array using the count variable f. But it seems my code is missing something and is showing an error on the browser. Thanks.

Upvotes: 0

Views: 157

Answers (8)

Angle
Angle

Reputation: 25

Try this(it display value with index)

$movies = array("one","two","three","four");
print_r($movies);

Upvotes: 0

Ali
Ali

Reputation: 5111

You can also populate index values of the array as follows:

<?php
    foreach($movies as $k => $movie){
        echo "Serial: ".$k;
        echo "Movie: ".$movie;
    }
?>

Upvotes: 1

Minciu
Minciu

Reputation: 96

Here are 2 options:

  1. using for loop:

    $movies = array("one","two","three","four");
    for($f=0; $f < count($movies); $f++)
    {
        echo $movies[$f];
    }
    
  2. using foreach loop:

    $movies = array("one","two","three","four");

    foreach($movies as $key=>$movie)

    {

    echo $movie;
    

    }

Upvotes: 1

Nanis
Nanis

Reputation: 361

$movies = array("one","two","three","four");
foreach ($movies as $value) {
    echo $value;
}

Look at : https://www.php.net/manual/en/control-structures.foreach.php

Upvotes: 0

Maarkoize
Maarkoize

Reputation: 2621

You can interate over the whole array with:

$movies_count = count($movies);
for($f=0; $f < $movies_count; $f++) {
    echo $movies[$f];
}

or use a foreach loop:

foreach($movies as $movie) {
    echo $movie;
}

Upvotes: 0

Suresh Kamrushi
Suresh Kamrushi

Reputation: 16076

try like this:

$count = count($movies);
for($f=0; $f < $count; $f++)

Upvotes: 0

Allen Chak
Allen Chak

Reputation: 1950

<?php
    foreach($movies as $movie){
        echo $movie;
    }
?>

Upvotes: 4

Muhammad Zeeshan
Muhammad Zeeshan

Reputation: 8856

   $movies = array("one","two","three","four");

    for($f=0; $f < count($movies); $f++)
    {
      echo $movies[$f];
    }

Upvotes: 0

Related Questions