array; if empty set to the first one

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
anotherJean
Forum Newbie
Posts: 22
Joined: Tue Mar 30, 2004 3:59 pm

array; if empty set to the first one

Post 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
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post by markl999 »

Maybe ...

Code: Select all

foreach($array as $key=>$val){
  if(empty($val)){
    $array[$key] = end(array_reverse($array));
  }
}
kettle_drum
DevNet Resident
Posts: 1150
Joined: Sun Jul 20, 2003 9:25 pm
Location: West Yorkshire, England

Post 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.
anotherJean
Forum Newbie
Posts: 22
Joined: Tue Mar 30, 2004 3:59 pm

Post 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
Post Reply