5
I’m trying to figure out a better or cleaner way to do something like this in PHP:
// Isto será passado como argumento de uma função...
$params = array('Nome', 'Idade', 'Mail' => '[email protected]');
"Name" and "Age" are values with automatically assigned keys (0 and 1, for example), and "Mail" is a key with the value "[email protected]":
[0] => 'Nome',
[1] => 'Idade',
['Mail'] => '[email protected]'
When I run this through a "foreach" loop, I’m doing this to have "Name" and "Age" as the actual parameters:
foreach ($params as $k => $i) {
// Esta é a parte "feia"!
if (is_int($k)) {
$k = $i;
$i = false;
}
// Para fazer algo assim, por exemplo...
$out = "";
if ($i) {
$out .= "<p><a href=\"mailto:$i\">$k</a></p>\n";
} else {
$out .= "<p>$k<p>\n";
}
}
What will return something like this:
<p>Name</p>
<p>Age</p>
<p><a href="mailto:[email protected]">Mail</a></p>
The question is: is there a clear way for PHP to differentiate the elements of the same array that have an explicit key (Mail => [email protected]) from those that do not (Name and Age)?
Observing: the above code was divided into two steps to better understand the current solution, which is to differentiate the value of the key by testing whether it is an integer, but the code I’m actually using is:
$o = "";
foreach ($params as $k => $i) {
if (!is_int($k)) {
$o .= "<p><a href=\"$i\">$k</a></p>\n";
} else {
$o .= "<p>$i</p>\n";
}
}
Wouldn’t it be more intuitive to have
array('Nome'=>null, 'Idade'=>null, 'Mail' => '[email protected]')
?– bfavaretto
@bfavaretto Yes, if this procedure was not within a generic function to, for example, create rows from a table, where the tag "td" might or might not have additional parameters. The ideal would be: funcao_tal('name', 'age', array('mail' => '[email protected]')), but I don’t know if there is a way for PHP to understand that the amount of arguments in the function may vary. At the same time, passing the entire argument as a single string and slashing it afterwards would be equally dirty. Note also that I’m wanting to take advantage of the new format of PHP arrays>=3.4 "[elements]", for the sake of readability.
– Blau
Don’t understand what you mean by dirty? Why not be dynamic? I see no problem in it, maybe it’s just your personal taste.
– Marcelo Aymone
To capture the arguments: http://php.net/manual/en/function.func-get-args.php
– Marcelo Aymone
@Marcelo Aymone, I just discovered this and in fact it is the solution. Thank you very much.
– Blau
I’m glad this helped find the answer, hugging!
– Marcelo Aymone