0

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.

1
  • what is the value of $result? Commented Feb 11, 2014 at 8:51

8 Answers 8

4
<?php
    foreach($movies as $movie){
        echo $movie;
    }
?>
Sign up to request clarification or add additional context in comments.

Comments

1

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;
    

    }

Comments

1

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

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

Comments

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

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

Comments

0

try like this:

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

Comments

0

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;
}

Comments

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

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

Comments

0

Try this(it display value with index)

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.