Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

My PHP Script

    $file_carrito=file("carrito.dat");

    $x=0;

    for($i=0;$i<sizeof($file_carrito);$i++)
    {
    $array_products_1[]=$file_carrito[$i];

    $x++;
    }



echo (array_count_values($array_products_1));  

In this simple file .dat , store all products the user add , and count in each case total of products for each id and case

For example i can have into the file 5 ids for one product and other 4 for other product id , finally , this must count products with te same id stored into de dat file

For example : 5 pencils , 3 chairs , 2 tables , etc .....

The problem it´s no works : echo (array_count_values($array_productos_1)); 



content of carrito.dat :

p1
p1
p1
p3
p3
p3
p2
p2
p2
p1
p1



With this function of array i want get :

Product p1 ---- (5)
Product p2 ----- (3) , etc

Thank´s

share|improve this question
    
You should show what carrito.dat looks like –  Sharlike Dec 12 '12 at 14:11
    
What does it do? "Doesn't work" isn't a problem description. –  deceze Dec 12 '12 at 14:15
    
Use sessions [local or server] better than relying on files. –  moonwave99 Dec 12 '12 at 14:16
    
I want file based server , in the file .dat each product use \n for separate and in the bucle i can recover these , before i create array and with this function i want count the products with the same id and get this value , thank´s regards –  user1860536 Dec 12 '12 at 14:32
    
this works with print_r but with echo (array_count_values($array_productos_1)); , no works –  user1860536 Dec 12 '12 at 14:33

2 Answers 2

The easy way:

$data = file('carrito.dat');

print_r(array_count_values($data));

It will show something like the below:

Array
(
    [p1] => 5
    [p3] => 3
    [p2] => 3
)
share|improve this answer
    
Yes but i need get normal values , no in this form , thank´s –  user1860536 Dec 12 '12 at 15:53
    
$data = file('carrito.dat'); $products = array_count_values($data); foreach ($product as $key => $value) { echo "Product $key ---- $value<br />"; } –  AlecTMH Dec 16 '12 at 18:20

count your values like this

$array = array('x', 'x', 'x', 'x', 'y', 'y');
$counts = array();
foreach($array as $value) {
    $counts[$value] = array_key_exists($value, $counts) ? $counts[$value]+1 : 1;
}

print_r($counts);

in your case. the array fill with

$array = explode("\n", file_get_contents(...));
share|improve this answer
    
Yes but i need get normal values , no in this form , no use print_r ..... thank´s –  user1860536 Dec 12 '12 at 15:54

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.