Martin AJ Martin AJ - 2 months ago 6
PHP Question

Can I pass an array instead of multiple related arguments to the function?

I have a function which provides a HTML for me. Something like this:

function user_profile ($name, $age, $location){
return "<div class='myclass' style='color:red'>
<span class='title'>user's profile</span>
<ul>
<li>Name: $name</li>
<li>Age: $age</li>
<li>location: $location</li>
</ul>
</div>";
}

echo user_profile ($name, $age, $location);


Function above is a simplified of my real function. In reality, that function has 14 arguments and the HTML is much more longer.

Anyway, I want to know can I make it more clean? I mean, can I make an array of all arguments and just pass it (the array)? In that case how can I use it into the function?

Again, in reality my code is much bigger and the above one is just a sample.

Answer

The answer is yes, you can pass an array as an argument. In your code it would look something like this:

function user_profile ($array){
    return "<div class='myclass' style='color:red'>
                <span class='title'>user's profile</span>
                <ul>
                    <li>Name: $array[0]</li>
                    <li>Age: $array[1]</li>
                    <li>location: $array[2]</li>
                </ul>
            </div>";
} 

//variables in the following array are defined elsewhere in script - not revelant here

$array = array($name, $age, $location);
echo user_profile($array);

A more attractive way to do this would be to use key-value pairs via an associative array:

function user_profile ($array){
    return "<div class='myclass' style='color:red'>
                <span class='title'>user's profile</span>
                <ul>
                    <li>Name: " . $array['Name'] . "</li>
                    <li>Age: " . $array['Age'] . "</li>
                    <li>location: " . $array['Location'] . "</li>
                </ul>
            </div>";
} 

//variables in the following array are defined elsewhere in script - not revelant here

$array = array('Name' => $name, 'Age' => $age, 'Location' => $location);
echo user_profile($array);

This method, using associative arrays, would allow you to more easily match array keys with the HTML list item content.

Comments