Here’s an example of what I mean:
I have an array:
array('type'=>'text',
'class'=>'input',
'name'=>'username',
'id'=>'username',
'value'=>'',
'size'=>'30',
'rows'=>'',
'cols'=>'');
Then, I loop through it like so:
$input = '<input ';
foreach($input_array as $key => $value) {
if(isset($key) && !empty($key)) {
$input .= $key . '="' . $value . '" ';
}
}
$input .= '/>';
I’m hoping to return:
<input type="text" class="input" name="username" id="username" size="30" />
I’ve tried using PHP’s sort() functions to no avail. The nearest I can figure is I’d need to use something like usort(), but I’m having trouble figuring how to write a function which will do what I want.
Any advice on this topic is greatly appreciated, and thanks very much for reading.
It should already be in that order. PHP arrays are sorted so the elements will be in the order in which you inserted them.
You also need to call
empty()on$valuenot$key;$keyshould always be non-empty. You also don’t needisset()as well asempty(). Apart from that your code works fine and produces the desired output.I would also be wary of using
empty()because it will return true for a string ‘0’. This could be a valid parameter value which would be ignored. You could instead check thatstrlen($value) > 0.