Page 1 of 1

array; if empty set to the first one

Posted: Tue Mar 30, 2004 3:59 pm
by anotherJean
hi :)

I haven't found anything about this topic, so I would like to ask here:

If an element of an array is empty, I would like to set that array to the first element.
What I mean is:
$array = array(

"red" => "car",
"blue" => "bike",
"white" => "",
)

so if "white" is empty I want to set it to the first one.
print $array['white'] ; // output : car

Thank you
anotherJean

Posted: Tue Mar 30, 2004 4:05 pm
by markl999
Maybe ...

Code: Select all

foreach($array as $key=>$val){
  if(empty($val)){
    $array[$key] = end(array_reverse($array));
  }
}

Posted: Tue Mar 30, 2004 4:41 pm
by kettle_drum
Should also check to make sure that the first value has a value - if not use the first element that has a value.

Posted: Tue Mar 30, 2004 8:19 pm
by anotherJean
Thanks for replies :)

Actually this is what I am already using. But I am not satisfied with that solution. It seems it slows down my server... (well I 've forgot to say that that array is huge...incredible huge.... ) 8)

I thought mayb there's sth build into the arrayfunctions, that jumps to the first (or next available) if any element is empty, but I didn't find anything practicable.

anotherJean