0

i want to find values in array according to alphabate and want to make list in of array values according to alphabate order.

my array is like that:

Array ( [0] => Array ( [0] => Adidas [1] => AKG [2] => Apple [3] => Barrats [4] => Canon [5] => Dell [6] => Dixons [7] => HTC [8] => Liverpool [9] => Microsoft [10] => Pirelli Tyres [11] => )

)

and i want to make a list of values according to alphabate like this:

A           
________        
  Adidas       
  AKG 

plz any idea?

7 Answers 7

1

You're after asort

asort($a);
foreach($a AS $v) {
    echo $v . "<br />";
}
Sign up to request clarification or add additional context in comments.

Comments

0

Could use some optimization, but does exactly what you asked:

    $a = array("Chicken","Fish","Hello","Lebowski","What","hey","foo");

    asort($a);
    $alphaArr = array();

    foreach(range('A', 'Z') as $letter) {

        // create empty array at offset for current letter
        $alphaArr[$letter] = array();

        foreach($a as $item) {

            // if the first letter starts with current letter
            // push it into subarray
            if (substr(strtolower($item),0,1) == strtolower($letter)) {
                $alphaArr[$letter][] = $item;
            }
        }
    }
    print_r($alphaArr);

2 Comments

@downvoter - What is the problem? Did you check the output? It is considered polite to explain why you down-voted, you know.
soory bass .. i dont vote down. i vote up.. sory if any mistake by me,,
0

Hardly comprehensible question, but I think you are looking for sort.

Comments

0

$fruits = array("lemon", "orange", "banana", "apple"); sort($fruits); reset($fruits); while (list($key, $val) = each($fruits)) { echo "fruits[".$key."] = ".$val."\n"; }

Comments

0

Your array is already sorted.

Get hold of the inner array and then loop over the values.

Whenever the first letter changes you know its the next letter.

1 Comment

ya, my array is already sorted .. bt i want to make list of values contain array according to alphabate A _____ abc apple acco like this
0

If you want to resort the list by the first letter of the company name, here's one way:

$sorted = array();
foreach($companies as $company) {
    $sorted[ strtoupper($company{0}) ][] = $company;
}

Comments

0

Just sort your array using sort() function and then print it out.
To have these letter captions just substr first letter and then compare to previou one:

$old='';
foreach ($words as $name) {
  if ($name[0] != $old) {
    echo $name[0]."<hr>\n";
  }
  echo $name."<br>\n";
  $old=$name[0];
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.