2010-03-13 12 views
5

Ich kenne die Funktion count() von php, aber was ist die Funktion zum Zählen, wie oft ein Wert in einem Array erscheint?Zählen Sie, wie oft ein bestimmter Wert in einem Array erscheint

Beispiel:

$array = array(
    [0] => 'Test', 
    [1] => 'Tutorial', 
    [2] => 'Video', 
    [3] => 'Test', 
    [4] => 'Test' 
); 

Jetzt will ich zählen, wie oft "Test" angezeigt wird.

Antwort

12

PHP hat eine Funktion namens array_count_values dafür.

Beispiel:

<?php 
$array = array(1, "hello", 1, "world", "hello"); 
print_r(array_count_values($array)); 
?> 

Ausgang:

Array 
(
    [1] => 2 
    [hello] => 2 
    [world] => 1 
) 
2

Versuchen Sie, die Funktion array_count_values können Sie hier weitere Informationen über die Funktion in der Dokumentation: http://www.php.net/manual/en/function.array-count-values.php

Beispiel von dieser Seite:

<?php 
$array = array(1, "hello", 1, "world", "hello"); 
print_r(array_count_values($array)); 
?> 

Wird produziert:

Array 
(
    [1] => 2 
    [hello] => 2 
    [world] => 1 
) 
Verwandte Themen