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 keys assigned automatically (0 and 1 for example), and "Mail" is a key with the value "[email protected]":
[0] => 'Nome',
[1] => 'Idade',
['Mail'] => '[email protected]'
When I pass 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 clean PHP way to differentiate the elements of the same array that have an explicit (Mail => [email protected]) key from the ones that do not have (Name and Age)?
The above code has been broken down into two steps to better understand the current solution, which is to differentiate the value of the key by testing if it is an integer, but the code that 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";
}
}