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

Kristian Woods
Kristian Woods
23,069 Points

Why would you want to change the name of the parameter?

I can follow along with the video, that is, until she changes the parameter name...

The function that was created to display HTML to the page:

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

  }

?>

This function is then used with a foreach loop:

 <?php
                    $random = array_rand($catalog, 4);
                    foreach($random as $id) {

                      echo get_item_html($id, $catalog[$id]);

                    }
 ?>

Then the output becomes:

    $output = "<li><a href='details.php?id="204"'><img src='"
        . $catalog[204]["img"] . "' alt='"
        . $catalog[204]["title"] . "' />" 
        . "<p>View Details</p>"
        . "</a></li>";

How can you get away with using different parameter names?

Can someone explain what is happening?

Thank you

1 Answer

Benjamin Payne
Benjamin Payne
8,138 Points

Hey Kristian,

Have a look at this Stack Overflow question. Basically, the function definition defines the parameters to be used inside the function. So where you defined get_item_html($id, $item) anything inside this function has to refer to $id or $item. When you are actually calling that function and passing arguments to it, you can call the arguments whatever you want or just pass the appropriate type directly into the function. For example:

<?php

function foo($hello, $world)
{
    echo $hello . ' ' . $world;
}

foo ("hello", "world");

// or

$bar = "hello"; // argument 1

$baz = "world"; // argument 2

foo ($bar, $baz);

Hopefully that helps.

Thanks,

Ben