if $x[1]=5; $x[2]=5; $x[3]=7; $x[4]=7; $x[5]=5; $x[6]=5; $x[7]=5; $x[8]=7; the numbers only 5 & 7 how to echo "2";( it means only 2 kind of nubmers)
<?php $y = array(); foreach($x as $val) { $y[$val] = true; } $uniques = count($y); unset($y); ?> PHP:
y is array of unique numbers. after the foreach loop, the y array should look like this: Array ( 5=>true, 7=>true ) so, value of $unique is 2
It loops through the source array one time. During this loop, it creates an array that uses the values of the source array as indexes. Since later occurrences of a value will already have a key in the new array, that existing key will just be overwritten preventing there from being any duplicates. Since there are no duplicates in the new array, it's safe to do a simple count() to get the unique element count before trashing the new array if there's no further need for it.
wow, nearly a perfect description of the buildin array_count_values() php function... Oh.. there is a little difference, the array_count_values() will have the count vor each key as value.... here, this work: <?php $x[1]=5; $x[2]=5; $x[3]=7; $x[4]=7; $x[5]=5; $x[6]=5; $x[7]=5; $x[8]=7; $y=array_count_values($x); $xcount= count($y); # $xcount is now the count of different values in $x print $xcount; ?> Code (markup):
5.2.9 PHP_FUNCTION(array_count_values) { zval **input, /* Input array */ **entry, /* An entry in the input array */ **tmp; HashTable *myht; HashPosition pos; /* Get arguments and do error-checking */ if (ZEND_NUM_ARGS() != 1 || zend_get_parameters_ex(1, &input) == FAILURE) { WRONG_PARAM_COUNT; } if (Z_TYPE_PP(input) != IS_ARRAY) { php_error_docref(NULL TSRMLS_CC, E_WARNING, "The argument should be an array"); return; } /* Initialize return array */ array_init(return_value); /* Go through input array and add values to the return array */ myht = Z_ARRVAL_PP(input); zend_hash_internal_pointer_reset_ex(myht, &pos); while (zend_hash_get_current_data_ex(myht, (void **)&entry, &pos) == SUCCESS) { if (Z_TYPE_PP(entry) == IS_LONG) { if (zend_hash_index_find(Z_ARRVAL_P(return_value), Z_LVAL_PP(entry), (void**)&tmp) == FAILURE) { zval *data; MAKE_STD_ZVAL(data); ZVAL_LONG(data, 1); zend_hash_index_update(Z_ARRVAL_P(return_value), Z_LVAL_PP(entry), &data, sizeof(data), NULL); } else { Z_LVAL_PP(tmp)++; } } else if (Z_TYPE_PP(entry) == IS_STRING) { if (zend_symtable_find(Z_ARRVAL_P(return_value), Z_STRVAL_PP(entry), Z_STRLEN_PP(entry) + 1, (void**)&tmp) == FAILURE) { zval *data; MAKE_STD_ZVAL(data); ZVAL_LONG(data, 1); zend_symtable_update(Z_ARRVAL_P(return_value), Z_STRVAL_PP(entry), Z_STRLEN_PP(entry) + 1, &data, sizeof(data), NULL); } else { Z_LVAL_PP(tmp)++; } } else { php_error_docref(NULL TSRMLS_CC, E_WARNING, "Can only count STRING and INTEGER values!"); } zend_hash_move_forward_ex(myht, &pos); } } Code (markup):