5
  • I need to create brand for an eCommerce site.
  • I need a solution that gives me first character from an array.
  • I tried some code but it was not so useful.
  • I need brand like I mentioned bellow.

like

A Alpha Aloo Amakeaviral B Boki Bone 

my data coming from database, in a array. I need first character from array.

I tried:

$my_array = array("Alpha", "Aloo", "Amakeaviral", "Boki", "Bone"); for($i = 0; $i <= count($my_array); $i++){ $first_char = $my_array[$i]{0}; echo $first_char; } 

but this not working well. How can I do this?

1
  • you should use $my_array[$i][0]. Also your loop is wrong it should be $i < count($my_array). Commented Sep 16, 2014 at 6:24

8 Answers 8

11

Try with substr() as simply short

$my_array = array("Alpha", "Aloo", "Amakeaviral", "Boki", "Bone"); foreach($my_array as $v){ echo substr($v, 0, 1); } 

or your code:- remove = from loop <=(else you will get notices) and use [] rather {}

$my_array = array("Alpha", "Aloo", "Amakeaviral", "Boki", "Bone"); for($i=0; $i < count($my_array); $i++){ $first_char = $my_array[$i][0]; echo $first_char; } 
Sign up to request clarification or add additional context in comments.

Comments

3

hope this will work for you -

$my_array = array("Alpha","Aloo","Amakeaviral","Boki","Bone"); $newArray = array(); foreach($my_array as $value) { $first_char = $value[0]; if (!empty($newArray)) { $flag = false; foreach ($newArray as $key => $val) { if ($first_char == $key){ $newArray[$key][] = $value; $flag = true; } } if (!$flag) { $newArray[$first_char][] = $first_char; $newArray[$first_char][] = $value; } } else { $newArray[$first_char][] = $first_char; $newArray[$first_char][] = $value; } } var_dump($newArray); 

Same as above but shortened code:

$my_array = array("Alpha","Aloo","Amakeaviral","Boki","Bone"); $newArray = array(); foreach($my_array as $value) { if (empty($newArray[$value[0]])){ $newArray[$value[0]][]=$value[0]; } $newArray[$value[0]][] = $value; } var_dump($newArray); 

6 Comments

omg so much code? Try foreach($my_array as $value) { if (empty($newArray[$value[0]])){ $newArray[$value[0]][]=$value[0]; } $newArray[$value[0]][] = $value; } for same efect!
@bansi hope you can do what is wanted in much less code and add the answer. i couldnt.
I can add the shortened version to this answer
the above will be an array with indexes with the first character.for the next array how can you differentiate the first character if needed with the values?
$value[0] is first character and it is used for the array key.So you will be storing the correct value to the correct key always!
|
3

substr

Finding first character

substr("Hello", 0, 1); //output "H" 

Try:

$first_char = substr($my_array[$i], 0, 1); 

Full code:

for($i = 0; $i < count($my_array); $i++){ echo $first_char = substr($my_array[$i], 0, 1); } 

Note: $i <= count($my_array) should be $i < count($my_array)

Live DEMO

Comments

2

Basically, every string is an array and can be accessed like it:

$str = 'This is a string'; echo $str[0]; // Output: T echo $str[1]; // Output: h echo $str[2]; // Output: i 

Just change this:

$first_char = $my_array[$i]{0}; 

into this:

$first_char = $my_array[$i][0]; 

Comments

2

Try this

$my_array = array("Alpha", "Aloo", "Amakeaviral", "Boki", "Bone"); foreach($my_array as $v){ echo $v[0]; } 

Comments

2

I know this is a bit old I'm sorry but this is how I did it with an array of objects. I wanted to display the title of each object in an alphabetised page. I used the following:

$items = array ( [0] => stdClass Object ( [title] => Alpha [name] => Joe Blogs [address] => 123 Harry Street ) [1] => stdClass Object ( [title] => Bravo [name] => Jane Doe [address] => 456 Upton Street ) [2] => stdClass Object ( [title] => Charlie [name] => Jane Doe [address] => 456 Upton Street ) ) 

Then declared this function in a helper class

public static function alphaSortItems ($items) { $sortedItems = array(); foreach ($items as $item) { $sortedItems[$item->title[0]][] = $item; } return $sortedItems; } 

Then to display them I used

 <?php $sortedItems = Helper::alphaSortItems($this->items); ?> <?php foreach ($sortedItems as $key => $value) : ?> <h2><?php echo $key; ?></h2> <?php foreach ($value as $item) : ?> <h3><?php echo $item->title; ?></h3> <?php endforeach; ?> <?php endforeach; ?> 

That's how I did it anyway :-)

Comments

1

Please try this:

$my_array = array("Alpha", "Aloo", "Amakeaviral", "Boki", "Bone"); for($i = 0; $i < count($my_array); $i++){ $first_char = $my_array[$i][0]; echo $first_char; } 

2 Comments

<= you will get undefined index notice?
Hey @Riteshdjoshi, I just did some formatting changes, just to make it look a bit more beautiful, nothing else!
0

Question is not very clear: I'm not getting if the OP wants the results grouped by initial letter and sorted, or only obtain the first letter.

Extract first letter from every word in the array

Basic concept

As others stated, a string can be seen also as an array of characters. In this case, we need to take the first character only (at index 0):

$word = 'cat'; $initial_letter = $word[0]; // result: 'c' 

Repeat for every item

In order to apply this to every word in the array, we can use array_map(callback, $array) which applies a callback function, to every item in the array.

So:

$my_array = ["Alpha", "Aloo", "Amakeaviral", "Boki", "Bone"]; array_map(fn($word) => $word[0], $my_array); // result: ['A', 'A', 'A', 'B', 'B']; 

If you want to return the first letter in uppercase format:

$my_array = ['alpha', 'omega']; array_map(fn($word) => strtoupper($word[0]), $my_array ); // result: ['A', 'O']; 

Sort words by initial letter

We can sort/divide the words array into groups, by their initial letter.

This is the expected format: [ 'A' => [word1, word2, word3, ...], 'B' => [word1, word2, ...] ]

$my_array = ["Alpha", "Aloo", "Amakeaviral", "Boki", "Bone"]; $grouped_word_list = []; foreach($my_array as $word) { $word_initial = strtoupper($word[0]); $grouped_word_list[$word_initial][] = $word; } 

To sort the result, you can sort the initial array this way:

sort($my_array); // it will modify the original array, don't assign result to a variable 

Why sorting the initial array instead of sorting the final list?

  • because sorting an unidimensional array is much easier and fast than sorting an associative array
  • words will be in the right sequence when they're moved into their group (by initial letter)

Full example

 $my_array = [ 'Alpha', 'Amakeaviral', 'Boki', 'Bone', 'Aloo', 'Zeta' ]; // Sort words in the array sort($my_array); // Get words grouped by initials $grouped_word_list = []; foreach ( $my_array as $word ) { $word_initial = strtoupper($word[0]); $grouped_word_list[ $word_initial ][] = $word; } // Print result var_dump($grouped_word_list); 

2 Comments

"Question is not very clear" Kind advice: don't answer it. And is a new answer really useful here?
Yes, it is in my opinion, because the other are using custom logic, I just wanted to show how the problem can be splitted into smaller parts and solved using native php functions.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.