简体   繁体   中英

Excluding numbers from an array

The code below returns a table with a row for every word or number that appears in $commentstring . Each word or number appears as $word in the table below. How can I exclude numbers?

$words = explode(" ", $commentstring);



    $result = array_combine($words, array_fill(0, count($words), 0));

    arsort($words);


    foreach($words as $word) {
    $result[$word]++;

    arsort($result);

    }


    echo "<table>";

    foreach($result as $word => $count1) {


    echo '<tr>';    
    echo '<td>';
    echo "$word";
    echo '</td>';

    echo '<td>';
    echo "$count1 ";
    echo '</td>';

    echo '</tr>';

    }

    echo "</table>";

You could use is_numeric to check whether each $word is a number, and only insert it into your array if it isn't.

if (!is_numeric($word)) {
    if (!isset($result[$word]))
        $result[$word] = 0;
    $result[$word]++;
    arsort($result);
}

Edit: Also, do you really need to sort the array on each increment? Why not just sort it at the end?

If i'm understanding your question right you can check if the $word var is a number by using the is_numeric() function

foreach($result as $word => $count1) {
    if(is_numeric($word)) { continue; }
    ...

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