php - How can I sort the results of a for each loop?

598

I have a list of stringsvar_dump($key):

string(6) "samuel"
string(4) "john"
string(4) "alan"
string(5) "frank"
string(3) "bob"

They are a result of a loop from a multidimensional array:

foreach ($array as $key => $item) { 
   if(is_array($item)){
      if (stripos($key, $keySearch) !== false){
      var_dump($key);
      }
   }
}

Is it possible to sort this list of strings?

I tried:

   foreach ($array as $key => $item) {  
       if(is_array($item)){
          if (stripos($key, $keySearch) !== false){
          asort($key);
          var_dump($key);
          }
       }
    }

and also

foreach ($array as $key => $item) {  
       if(is_array($item)){
          if (stripos($key, $keySearch) !== false){
              array_multisort($key);
              var_dump($key);
          }
       }
    }

My sort attemts are not working. The problem is I cannot sort thearray because it is a complex multidimensional array. So I somehow only want to sort the results. But I am not sure how to do that.

The result I wish forvar_dump($key) would be:

string(4) "alan"
string(3) "bob"
string(5) "frank"
string(4) "john"
string(6) "samuel"
252

Answer

Solution:

PHP - Sort Functions For Arrays

sort() - sort arrays in ascending order
rsort() - sort arrays in descending order
asort() - sort associative arrays in ascending order, according to the value
ksort() - sort associative arrays in ascending order, according to the key
arsort() - sort associative arrays in descending order, according to the value
krsort() - sort associative arrays in descending order, according to the key

People are also looking for solutions to the problem: Remove Specific key value pair from PHP array

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.