Reputation: 6707
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.
Upvotes: 1
Views: 224
Reputation: 426
In my opinion, Passing array as an argument is the only clean way to do as The One and Only ChemistryBlob said. But can be improved by let it be more dynamic as array can be passed with any number of information.
function user_profile ($array){
$return ="<div class='myclass' style='color:red'>
<span class='title'>user's profile</span>
<ul>".PHP_EOL;
foreach($array as $key=> $value){
$return .="<li>".$key.": ".$value."</li>".PHP_EOL;
}
$return.="</ul>
</div>";
return $return;
}
$try =['Name' => $name,
'Age' => $age,
'Location' => $location];
echo user_profile($try);
Upvotes: 0
Reputation: 7884
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.
Upvotes: 3