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?
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;
}
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);
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)
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];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With