In this session we will study the looping statements in php such as for and while loop.
- To study the looping statements follow the steps given below :
-
- Install the Xampp server , if it is already installed then go to xampp folder .
-
- Inside this xampp folder you will have htdocs folder .
-
- In this htdocs folder create a new folder say s4
-
- Inside this s4 folder create a new file say index.php and open it with Notepad++ or any other text editor.
-
- So to implement the loops write the following code in index.php file :
<html> <body> <h1>This is the for loop</h1> <?php for($i=0;$i<=10;$i++) { echo 'Number ' .$i .'<br />'; } ?> <h1>This is the while loop</h1> <?php $i=0; while($i <= 10){ echo 'number '.$i.'<br />'; $i++; } ?> </body> </html>
-
- You will have the following view of your Notepad++ window :
-
- Now open up the browser and enter the following url in the address bar : http://localhost//s4//index.php
-
- You will have the output as shown below :
- Implement Loops in php using Json
-
- Create an new folder in the htdoc say s5 inside that create an new file called as index.php and open it with notepad++ and write the given code in it
<?php $jsondata = file_get_contents("movies.json"); $json = json_decode($jsondata,true); ?> <!DOCTYPE html> <html> <head> <title>My Movies</title> </head> <body> <div id="container"> <h1>My Favorite Movies</h1> <ul> <?php //echo $json['movies'][0]['title']; foreach($json['movies'] as $key => $value){ echo '<h4>'.$value['title'].'</h4>'; echo '<li>Year: '.$value['year'].'</li>'; echo '<li>Genre: '.$value['genre'].'</li>'; echo '<li>Director: '.$value['director'].'</li>'; } ?> </ul> </body> </html>
-
- Now in the same s5 folder create another file say movies.json , open it with notepad++ and write the given code in it :
{ "movies": [ { "title": "The Godfather", "year": "1972", "genre": "Drama", "director": "Francis Ford Copolla" }, { "title": "Superbad", "year": "2007", "genre": "Comedy", "director": "Greg Mottola" }, { "title": "The Departed", "year": "2006", "genre": "Drama", "director": "Martin Scorsese" }, { "title": "Saving Private Ryan", "year": "1998", "genre": "Action", "director": "Steven Spielberg" }, { "title": "The Expendables", "year": "2010", "genre": "Action", "director": "Sylvester Stallone" } ] }
-
- The window look like as shown below :
-
- Now open up the browser and enter the url as http://localhost/s5/index.php
-
- You will have the following output :
-
- You can add the css in head section
<style> h1{text-align:center;} h4{margin:0;padding:5px;background:#f4f4f4;} li{list-style:none;padding-left:5px;} #container{width:600px;margin:auto;overflow:hidden;} </style>
-
- Now run the project and you will have the following output window :-
- Thus we have learnt implementing loops in php using json.