User Tools

Site Tools


en:web_development:media:named_arrays

This is an old revision of the document!


Web Development Lesson 6 - Media

Named Arrays

Objective

In this activity you will learn some advanced array techniques for arrays in PHP, which will be useful when processing data from a database.

Setup

  • We will continue using 'media.php' and 'style.css' in Visual Studio Code. Here's the code again if you need it.

media.php

<?php
    $page = "media";
    include("header.php");
    include("menu.php");

    $photos = array("https://images.pexels.com/photos/674010/pexels-photo-674010.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500",
                    "https://images.ctfassets.net/hrltx12pl8hq/61DiwECVps74bWazF88Cy9/2cc9411d050b8ca50530cf97b3e51c96/Image_Cover.jpg?fit=fill&w=480&h=270",
                    "https://images.ctfassets.net/hrltx12pl8hq/3MbF54EhWUhsXunc5Keueb/60774fbbff86e6bf6776f1e17a8016b4/04-nature_721703848.jpg?fit=fill&w=480&h=270",
                    "https://cdn.pixabay.com/photo/2021/08/25/20/42/field-6574455__340.jpg",
                    "https://www.gettyimages.es/gi-resources/images/500px/983794168.jpg",
                    "https://media.istockphoto.com/photos/concept-of-an-open-magic-book-open-pages-with-water-and-land-and-picture-id1279460648?b=1&k=20&m=1279460648&s=170667a&w=0&h=uZa830sWo8hlFN0Y7FnQ14giNC0Z2EBNuTMuNJeJhQg=");
?>
    <main>
        <img src="https://cdn.pixabay.com/photo/2015/04/23/22/00/tree-736885__480.jpg" alt="tree at sunset" title="this was the first image listed on Google when I checked">
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec enim sem, efficitur et fringilla et, pretium at turpis. Nunc interdum, dolor vitae aliquam accumsan, lacus sapien varius tortor, fringilla lobortis turpis tortor et ante. In hac habitasse platea dictumst. Nullam elementum blandit tincidunt. Sed semper finibus massa, non mollis nulla mollis et. Nunc lectus metus, tempor nec dui ut, pharetra eleifend massa. Ut tempus porta metus, eget aliquet ligula tempor hendrerit. Curabitur vestibulum elit in commodo viverra. Nullam est orci, suscipit vitae tincidunt porta, lacinia sed nulla. Quisque ex eros, consectetur id metus sit amet, molestie tempor risus. In facilisis consequat eros in convallis. Nulla nec imperdiet nibh. Suspendisse consequat sit amet mi in imperdiet. Nullam eget aliquet metus. Vestibulum non fermentum eros. Cras sodales, nisl eget congue interdum, massa nulla porta lectus, quis suscipit est ipsum sit amet ante.</p>
        <p>Morbi gravida malesuada odio, sed pretium libero aliquam vitae. Suspendisse potenti. Nunc eget leo vulputate, dictum eros non, gravida lorem. In id nunc id orci ornare porttitor. Maecenas id laoreet risus. Aenean lacinia dignissim volutpat. Morbi et ligula ac purus gravida aliquet. Integer feugiat sapien ac porttitor iaculis.</p>
        <video src="http://it.bibliotecasmedellin.gov.co/bibliolabs/numeros/1.mp4" controls muted loop autoplay></video>
        <p>Phasellus pretium sit amet tellus ac tincidunt. Curabitur in ligula massa. Vivamus in urna suscipit, vehicula velit et, mollis purus. Aliquam sed risus vel urna tristique aliquam. Etiam egestas lectus arcu, quis lobortis diam luctus in. Vivamus id diam metus. Nulla bibendum dolor sit amet egestas semper. Praesent facilisis pellentesque condimentum.</p>
        <p>Mauris ac sapien justo. Curabitur a feugiat velit. Donec non mi ac turpis faucibus hendrerit. Nulla luctus est lectus, nec rhoncus nisi eleifend ac. Nullam iaculis mi eget faucibus mattis. Nullam nec cursus nisi. Donec vel nunc ac felis sodales tincidunt sed condimentum mauris.</p>
        <p>Praesent lobortis dictum purus, convallis dapibus velit malesuada non. Sed sit amet magna sagittis, maximus odio in, mattis erat. Phasellus ultricies risus turpis, vitae tempor diam finibus eu. Sed luctus augue purus, eget consectetur sapien egestas et. Sed eget tristique mauris. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum rhoncus vehicula pellentesque. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia curae; Aenean placerat arcu vitae nisi vehicula semper. Cras sit amet risus dolor.</p>
        <audio src="https://freesound.org/data/previews/611/611814_13567802-lq.mp3" controls loop></audio>
        <input type="button" value="Play Audio" onclick="playPauseAudio()">
        <div id="album">
<?php
    for($i = 0; $i < 6; $i++) {
        error_log('MURRAY ' . $photos[$i]);
        echo "\t\t\t<img src='$photos[$i]'>\n";
    }
?>
        </div>
    </main>
<?php
    include("footer.php");
?>

style.css

ol {
    color: blue;
  }
  
  ol ol {
    font-weight: 700;
  }

ul {
  list-style-type: none;
}

td, th {
  border-width: 1px;
  border-style: solid;
}

td {
  padding: 10px;
}

table {
  border-collapse: collapse;
}

header {
  background-color:indianred;
  border:darkred solid 2px;
  height: 100px;
  position: absolute;
  left: 16%;
  right: 0px;
  top: 0px;
}

nav {
  background-color: burlywood;
  border:yellow solid 2px;
  position: fixed;
  top: 0px;
  bottom: 0px;
  width: 16%;
  left: 0px;
}

main {
  background-color: lightgree;
  border: darkgreen solid 2px;
  position: absolute;
  top: 100px;
  left: 16%;
  right: 0px;
  bottom: 80px;
  overflow: scroll;
  padding: 20px;
}

footer {
  background-color: lightskyblue;
  border: darkblue solid 2px;
  position: absolute;
  bottom: 0px;
  height: 80px;
  left: 16%;
  right: 0px;
}

.content {
  background-color:coral;
  border:orangered solid 2px;
  height: 400px;
  padding: 40px;
  margin: 20px;
  display: inline-block;
  width: 300px;
}

img {
  float: left;
  max-height: 250px;
  border: solid 2px green;
  margin: 20px 20px 20px 0px;
  padding: 10px;
  border-radius: 30px;
}

#album {
  display: flex;
  justify-content:space-between;
  flex-wrap: wrap;
}

video {
  max-height: 250px;
  float: right;
  clear: left;
  margin: 20px 0px 20px 20px;
  padding: 10px;
}

audio {
  margin: 20px 20px 20px 0px;
  padding: 10px 10px 10px 0px;
}

input[type=button] {
  display: block;
}

Named Arrays

  • We've seen how to create an array in PHP like this.
$animals = array('dog', 'elephant', 'rabbit');
  • This allows us to access each item in the array by number ($animals[0]).
  • For greater flexibility, in PHP (unlike in Javascript) we can assign names for each element.
    $animals = array('item1' => 'dog', 'item2' => 'elephant', 'item3' => 'rabbit');
  • Update the '$photos' array in 'media.php' to take advantage of this format.
    $photos = array("Photo 1" => "https://images.pexels.com/photos/674010/pexels-photo-674010.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500",
                    "Photo 2" => "https://images.ctfassets.net/hrltx12pl8hq/61DiwECVps74bWazF88Cy9/2cc9411d050b8ca50530cf97b3e51c96/Image_Cover.jpg?fit=fill&w=480&h=270",
                    "Photo 3" => "https://images.ctfassets.net/hrltx12pl8hq/3MbF54EhWUhsXunc5Keueb/60774fbbff86e6bf6776f1e17a8016b4/04-nature_721703848.jpg?fit=fill&w=480&h=270",
                    "Photo 4" => "https://cdn.pixabay.com/photo/2021/08/25/20/42/field-6574455__340.jpg",
                    "Photo 5" => "https://www.gettyimages.es/gi-resources/images/500px/983794168.jpg",
                    "Photo 6" => "https://media.istockphoto.com/photos/concept-of-an-open-magic-book-open-pages-with-water-and-land-and-picture-id1279460648?b=1&k=20&m=1279460648&s=170667a&w=0&h=uZa830sWo8hlFN0Y7FnQ14giNC0Z2EBNuTMuNJeJhQg=");

Displaying Arrays

  • Now, let's display this inside the <main> tag.
  • echo $photos; won't work. When you view the page, you'll see the word 'Array' only because echo only prints strings.
  • Try this instead.
    print_r($photos);
  • print_r displays more complex structures including arrays.
  • When you view the page, you'll see some complicated text that looks something like the array.
  • To see it properly, right click on the page and select 'View Page Source'.
  • Now the formatting is much better and you can clearly read the array.
  • This is one way to create such an array, We can also assign each item separately.
    $animals['item1'] = 'dog';
    $animals['item2'] = 'elephant';
    $animals['item3'] = 'rabbit';
  • We can read the array in the same way. Add this code to the <main> tag.
    echo "MURRAY: the first photo is {$photos['Photo 1']}.";
  • Now view the page and check the results.

Foreach

  • We've seen how to do a 'for loop' in the previous activity, but there's another loop that is extremely useful for processing arrays. It's the 'foreach' loop.
  • Add the following PHP code to the <main> tag after creating your array.
    foreach($photos as $name => $link) {
        echo "MURRAY: $name is a $link";
    }
  • The first line sets up the loop. It says 'run through this code for each item in the array $photos, where the reference for each item is $name and the item itself is $link'.
  • We can now refer to the name and the actual item by using the variables $name and $link.
  • echo can then display these values so that we can read them in the HTML code.
  • Try it now to be sure you understand it.
  • When you're ready, add the following code to display the photos along with the respective names.
<?php
    foreach($photos as $name => $link) {
?>
            <figure>
                <img src='<?php echo $link; ?>' alt='<?php echo $name; ?>'>
                <figcaption><?php echo $name; ?></figcaption>
            </figure>
<?php
    }
?>
  • There are a couple of things to note here.
  • We've used a couple of new HTML tags. <figure> is a block element that can be used to present an image and a caption. <figcaption> is used to hold the caption for an image.
  • Secondly, we've changed the way we encode the HTML block. Rather than include all the HTML inside a string, which requires us to add \t and \n to make it readable in the View Page Source view, we've left the HTML as is and created a new PHP block for each variable to be displayed.
  • This is much more readable for me.
  • Refresh your page and check that it works as it should.
  • It needs a bit of styling. Try this or add your own.
figcaption {
  display: block;
  text-align: center;
  font-family: 'Arial', sans-serif;
  color: green;
}

While Loop

  • Just as in Javascript, PHP has many types of loops. The next we'll look at is the 'while loop'.
  • Add the following code inside a PHP block. It might be best to put it at the end to keep it separate. Change my name to yours so you can find your results in the logs.
    $i = 0;
    while ($i < 10) {
        error_log("MURRAY: the value of i is $i");
        $i++;
    }
  • $i = 0; defines a variable and sets it to '0'.
  • while ($i < 10) {} runs the code inside {} as long as $i is less than 10.
  • error_log("MURRAY: the value of i is $i"); outputs a string containing the value of $i to the logs so we can see it.
  • Finally, $i++; increments $i each loop so that it doesn't go on forever.
  • Open the page 'mysql.php' and check your logs using Putty.
cat /var/log/apache2/error.log | grep 'MURRAY'
  • You should see your text ten times with the number increasing from 0 to 9.
  • So this is another way of running the same code multiple times.

Next: Exercises

en/web_development/media/named_arrays.1651587567.txt.gz · Last modified: 2023/08/16 09:33 (external edit)