Hey just another quick question reagrding arrays.

is there a way to count the number of elements in my array.

so for example

my array is as so

$array = array("1", "1", "2", "3", "4", "1");

i need it to output

1 = 3
2 = 1
3 = 1
4 = 1

well along those lines any way similar to the count function in mysql.

cheers 😃

    print_r(array_count_values($array));

      cheers for that works a treat, one other thing is there a way of displaying the results in a more user friendly manor or do u have to use print_r?

      cheers again

        Something more user-friendly?

        Hmm...

        Maybe this will work for you:

        <?php
        $num_array = array(1, 1, 2, 3, 4, 1, 2, 3, 3, 3, 4, 5, 18, 5);
        
        $num_count = array();
        
        foreach($num_array as $value) {
        
        if(!isset($num_count[$value]))
        {
        	$num_count[$value] = 1;
        }
        else
        {
        	$num_count[$value] = $num_count[$value] + 1;
        }
        }
        
        foreach($num_count as $key=>$value)
        {
        	echo $key . ' = ' . $value . '<br />';
        }
        ?>
        

        You will have to forgive me if this is a silly way to do this: I am just waking up, LOL!!! 😃

          array_count_values() returns array - print_r() is the simplest method to view what are its values. Nevertheless you can use for, foreach, while loop... to display the result.

            konrad wrote:

            array_count_values() returns array - print_r() is the simplest method to view what are its values. Nevertheless you can use for, foreach, while loop... to display the result.

            Ahhh! I TOLD you I was just waking up!! LOL.... :p

            <?php
            $num_array = array(1, 1, 2, 3, 4, 1, 2, 3, 3, 3, 4, 5, 18, 5);
            
            $result = array_count_values($num_array);
            
            foreach($result as $key=>$value)
            {
            	echo $key . ' = ' . $value . '<br />';
            }
            ?>
            

              cheers rodney/conrad that works a treat thanks again.

                Write a Reply...