I have this foreach loop and i was wondering if there could be a way to sort the array accurding to a value if it's not empty to be at top and the rest goes down. here what I have done so far:
foreach ((array)$accounts as $v=>$k){
if(!empty($k)) {
echo $v;
echo "</br>";
echo $k;
echo "</br>";
} else {
echo $v;
echo "</br>";
}
}
Note: $k
returns either a string or it's just empty not NULL
The ouput is something like:
k1
v1
k2
k3
v3
As you can see k2
has no value. i want it to be at the bottom as it doesn't have a value.
Outputing the array directly with print_r($accounts, TRUE)
:
Array
(
[TwitterSecKey] => Twitter Sec Key
[GoogleSecKey] =>
[InstagramSecKey] => Instagram Sec Key
[FacebookSecKey] =>
)
As you can see Google and Facebook don't have values. so i want them to be at the bottom.
Thank you for finally providing your array structure.
Based on your requirement of:
sort the array accurding to a value if it's not empty to be at top and the rest goes down
There is no need for complicated sorting algorithms with uasort()
, please try this:
<?php
$accounts= array(
'TwitterSecKey'=>'Twitter Sec Key',
'GoogleSecKey'=>null,
'InstagramSecKey'=>'Instagram Sec Key',
'FacebookSecKey'=>null
);
echo '<pre>'.print_r($accounts, TRUE).'</pre>';
arsort($accounts); // secret sauce
echo '<pre>'.print_r($accounts, TRUE).'</pre>';
You can do this to sort your array using usort and then use them accordingly
$accounts = (array) $accounts;
usort($accounts, function($a, $b) {
return strlen($b) - strlen($a);
});
Now.
foreach($accounts as $k=>$v){
echo 'key: '. $k .'<br>';
echo 'value: '. $v .'<br>';
}
UPDATE To preserve keys you can use uasort as
$accounts = (array) $accounts;
uasort($accounts, function($a, $b) {
return strlen($b) - strlen($a);
});
You could use a custom function with uasort
, which puts empty values last, but sorts all the rest alphabetically:
$accounts = array (
'x' => 'c',
'y' => 'a',
'z' => 'b',
'n' => '',
);
uasort($accounts, function($a, $b) {
return empty($a) ? 1 : (empty($b) ? -1 : strcmp($a,$b));
});
var_export($accounts);
Output:
array (
'y' => 'a',
'z' => 'b',
'x' => 'c',
'n' => '',
)