PHP Build a Basic PHP Website (2018) Listing and Sorting Inventory Items Random Fun with Arrays

john paul
john paul
3,191 Points

Clarification needed please

Might be a stupid question .. but this will help me to complete the dots.

I fully understand the code and the way it works in index.php with regard to the use of array_rand, the creation of the array $random, the foreach loop and the assignment of $random to the variable $id and then we pass the two parameters into our get_item_html function i.e. we pass $id and $catalog[$id] into the function.

My question is this; in the functions.php file we define our function

<?php
function get_item_html($id,$item) {
  $output = "<li><a href='#'><img src='"
        . $item["img"] . "' alt='"
        . $item["title"] . "' />"
        . "<p>View Details</p>"
        . "</a></li>";
    return $output;
}

is there any relationship between the first function parameter $id? and $id defined in the index.php? Could the first parameter in the functions file have been called $key instead? and the variable $id in index.php would still have worked? Did they need to be called the same variable name?

cheers

2 Answers

For simplicity and to avoid confusion, it's best to keep the same variable names in the function parameter when calling the function. You can change it to get_item_html($key,$item) and that will not change the result as long it gets the expected variable (an int or string... )

If it expects a string and you pass an array, then that would be an issue.

john paul
john paul
3,191 Points

Many thanks, I thought as much, but wanted to be sure.

best

John