<?php
function filter($fst, $arr){
$new_arr=array();
for($i=0;$i<=(count($arr)-1);$i++){
if(substr($arr[$i], 0, 1) == $fst){
$new_arr[] = $fst;
}
}
return $new_arr;
}
$list = Array("Apparel","Associations","Building/Grounds","Building/Materials",
"Dispensing","Disposables","Distributors");
$new_list[]=filter("A", $list);
for($i=0;$i<=(count($new_list)-1);$i++){
echo '<li><a href="?id='.$i.'">'.$new_list[$i].'</a></li>';
}
?>
I have created a function named filter() to filter the contents of an array that starts with a character like “a”. It does not work at the moment.
First of all I assume that you want to print the word that was OK and not the character you was checking with?
$new_arr[] = $fst;should be$new_arr[] = $arr[$i];Secondly you’re adding the resulting array of the function into a new array instead of assigning the array to your variable.
$new_list[] =should be$new_list =.Here’s an updated version of your code. I’ve marked where I’ve made changes..
Output: