简体   繁体   中英

I want to filter an array by first letter in PHP

<?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
don't use

$new_list[] = filter("A", $list);

but simply

$new_list = filter("A", $list);

because your code will try to put an $new_array from filter() into next free index in array variable $new_list

second

$new_arr[] = $fst;

is wrong, because you're setting as new array value the A not matching word. use this instead:

$new_arr[] = $arr[$i];

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..

function filter($fst, $arr){
$new_arr=array();

    for($i=0;$i<=(count($arr)-1);$i++){
        if(substr($arr[$i], 0, 1) == $fst){
            $new_arr[] = $arr[$i];         <----- Changed here
        }
    }
    return $new_arr;
}



$list = Array("Apparel","Associations","Building/Grounds","Building/Materials",
              "Dispensing","Disposables","Distributors");

$new_list=filter("A", $list);  <----- And changed here

for($i=0;$i<=(count($new_list)-1);$i++){ 
    echo '<li><a href="?id='.$i.'">'.$new_list[$i].'</a></li>'; 
}

Output:

<li><a href="?id=0">Apparel</a></li>
<li><a href="?id=1">Associations</a></li>
for($i=0;$i<=(count($arr)-1);$i++){
    if(substr($arr[$i], 0, 1) == $fst){
        //$new_arr[] = $fst; // <-- Bug is here
        $new_arr[] = $arr[$i]; // Try this
    }
}

And another bug:

//$new_list[]=filter("A", $list); // This
$new_list = filter("A", $list); // Should be this
foreach($arr as $word) {
  // do something with $word
}

reads better than a C-style for $i loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM