PHP: elements with and without explicit keys in the same array

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 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";
    }
}
    
asked by anonymous 31.07.2014 / 16:43

2 answers

4

The answer to the original question is even no , there is no way for PHP to differentiate between elements with and without keys within the same array.

But the original problem stemmed from the need to create a readable function where the number of arguments passed might vary, hence the initial array option, which would allow a call like this:

add_table_row(['Nome', 'Idade', 'Mail' => '[email protected]']);

or so ...

add_table_row(array('Nome', 'Idade', 'Mail' => '[email protected]'));

However, as I have just discovered, there is a way to pass a variable amount of arguments to a function using the function "func_get_args ()", and the call of the function may become even more readable:

// PHP >= 5.4
add_table_row('Nome', 'Idade', ['Mail' => '[email protected]']);

or

add_table_row('Nome', 'Idade', array('Mail' => '[email protected]'));

So an example of the full function code would look something like this:

function add_table_row() {
    $args = func_get_args(); // retorna uma array de argumentos...
    $o = "<tr>\n";
    foreach ($args as $value) {
        if (is_array($value)) {       // Se o argumento é uma array...
            $cont = key($value);      // O dado da célula é a chave...
            $param = current($value); // E o parâmetro da tag é o valor...
            $o .= "<td $param>$cont</td>\n";
        } else {
            $o .= "<td>$value</td>\n";
        }
    }
    $o .= "</tr>\n";
    return $o;
}

I hope this is useful to someone else.

    
31.07.2014 / 17:50
0

Since you are going to create a function for this, you can pass as string and find the markers elements ... Just explode in , and if there is : the function will understand that it is an array. add_table_row('Nome,Idade,Mail:[email protected]')

    function add_table_row( $string )
    {
        $string = explode( ',' , $string );

        foreach( $string as $line )
        {
            if( strpos( $line , ':' ) && $elementos = explode( ':' , $line ) )
            {
                echo $elementos[0] . ', ' . $elementos[1];
            }
            else
            {
                echo $line;
            }
        }
    }
  

output
Name
  Age
  Mail, [email protected]

    
31.07.2014 / 22:26