0

I have a list array

array([img1] => "", [img2] => "AJKH.png", [img3] => "", [img4] => "")
array([img1] => "", [img2] => "AJKH.png", [img3] => "IHGF.png", [img4] => "")

How to reorder when some value in array are empty. How ideas?

array([img1] => "AJKH.png", [img2] => "", [img3] => "", [img4] => "")
array([img1] => "AJKH.png", [img2] => "IHGF.png", [img3] => "", [img4] => "")
user151841
  • 17,377
  • 29
  • 109
  • 171
Hai Truong IT
  • 4,126
  • 13
  • 55
  • 102
  • You can try sorting the array. Also if its fine, you can loop though the array and unset the empty spaces. – Ajit Kumar Singh Dec 17 '15 at 07:33
  • 9
    Take a look at http://stackoverflow.com/questions/9395395/php-how-to-move-the-empty-values-of-an-array-to-its-last-positions – Matt Dec 17 '15 at 07:33

2 Answers2

1

The proposed duplicate is almost the same, but this one seems a little different because it looks like you want to keep your keys in the same order (not maintain key-value association) and just move the values around based on whether or not they are empty. This should do that:

$new_array = array_fill_keys(array_keys($array), '');
foreach ($array as $value) {
    if ($value) {
        $new_array[key($new_array)] = $value;
        next($new_array);
    }
}
Don't Panic
  • 41,125
  • 10
  • 61
  • 80
0

An easy approach is to have 2 arrays and merge them (it will be better, rather than swapping in terms of computation).

$empty=array();
$full=array();

foreach($yourArray  as $value){
if($value==""){
    $empty[]=$value;
}
else{
   $full[]=$value;
}
}

$result = array_merge($full, $empty);

Another approach is to write an algorithm that will check the position of the element (empty) and swap them. Bring all the empty on the end.

Danyal Sandeelo
  • 12,196
  • 10
  • 47
  • 78