How can I move the empty values of an array to its last position?
For example:
$givenArray = array(
0=>'green',
1=>'',
2=>'red',
3=>'',
4=>'blue'
);
$requiredArray = array(
0=>'green',
1=>'red',
2=>'blue',
3=>'',
4=>''
);
Provided that the non empty values should not be sorted. It should be as it is, i.e. only the empty values should move to the end of an array.
I need exactly what my examples show.
There are much better/more elegant answers in this thread already, but this works too:
//strip empties and move to end
foreach ($givenArray as $key => $value)
{
if ($value === "")
{
unset($givenArray[$key]);
$givenArray[] = $value;
}
}
// rebuild array index
$givenArray = array_values($givenArray);
There is usort($array, $callback) function that will sort with your own custom callback.
Try using usort
.
function empty_sort ($a, $b) {
if ($a == '' && $b != '') return 1;
if ($b == '' && $a != '') return -1;
return 0;
}
usort($array, 'empty_sort');
Which gives (Demo):
Array
(
[0] => blue
[1] => green
[2] => red
[3] =>
[4] =>
)
$givenArray = array(
0=>'green',
1=>'',
2=>'red',
3=>'',
4=>'blue'
);
foreach($givenArray as $value){
if(empty($value)){
$newarray[] = $value;
}else{
$filledarray[] = $value;
}
}
$requiredArray = array_merge($filledarray,$newarray);
This should work:
function sortempty( $a, $b ) {
return empty( $a );
}
usort( $array, 'sortempty' );
Output (Demo):
Array
(
[0] => blue
[1] => green
[2] => red
[3] =>
[4] =>
)
usort()
allows you to sort an array using a user-defined function. I return if $a
is empty or not. If it's empty, return 1 which makes value $a
shift right (or down) in the array.
You are looking for all values not being an empty string (""
) first and then all values being an empty string:
$requiredArray = array_diff($givenArray, array(''))
+ array_intersect($givenArray, array(''));
This will give you:
array(5) {
[0]=> string(5) "green"
[2]=> string(3) "red"
[4]=> string(4) "blue"
[1]=> string(0) ""
[3]=> string(0) ""
}
Which has the benefit that it preserves key => value association. If you need to renumber the keys, just apply the array_values
function:
$requiredArray = array_values($requiredArray);
This will turn it into your required layout (Demo):
array(5) {
[0]=> string(5) "green"
[1]=> string(3) "red"
[2]=> string(4) "blue"
[3]=> string(0) ""
[4]=> string(0) ""
}