Question

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.

Was it helpful?

Solution

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 $value not $key; $key should always be non-empty. You also don't need isset() as well as empty(). 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 that strlen($value) > 0.

OTHER TIPS

Running the following code through PHP's interactive commandline just affirms Tom Haigh's statement

It should already be in that order. PHP arrays are sorted so the elements will be in the order in which you inserted them.

<?php
$a = array(
    'type'=>'text',
    'class'=>'input',
    'name'=>'username',
    'id'=>'username',
    'value'=>'',
    'size'=>'30',
    'rows'=>'',
    'cols'=>''
);
print_r($a);
/* 
Array
(
    [type] => text
    [class] => input
    [name] => username
    [id] => username
    [value] =>
    [size] => 30
    [rows] =>
    [cols] =>
) 
*/
foreach ($a as $k => $v) {
    echo $k . ' => ' . $v . "\n";
}
/* 
type => text
class => input
name => username
id => username
value =>
size => 30
rows =>
cols =>
*/

You're sure that this is exactly the code you're using and there is nothing happening to $input_array between creation and looping?

EDIT:

Just a simple and perhaps stupid question: Where do you check how the resulting string in $input looks like? If you do so in e.g. FireBug's HTML navigator the attributes' order won't match the real order in the HTML source as FireBug displays the DOM tree generated from the source (and potential Javascript manipulation) which means that it can reorder the attributes at will...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top