0

This is my code:

foreach($total_columns as $value){
    echo "<td><b>{$value}</b></td>";
}

Each $value is being echoed twice, one for the numerical key and one for the associative key. How do I stop this from happening?

Sw1sh
  • 21
  • 7
  • What does `$total_columns` contain? – Joe Jun 12 '13 at 13:22
  • `print_r($total_columns);` Is it what you expect? – Dale Jun 12 '13 at 13:24
  • It's an array of numbers and blank spaces. It contains the total of each column from a report,but if the report value isn't numeric it just has a blank space instead. – Sw1sh Jun 12 '13 at 13:25
  • Can you add the output of `print_r($total_columns);` to your question, it would really help us answer you :) – Dale Jun 12 '13 at 13:26
  • print_r($total_columns); gave me ... [13] => 100 [goods_total] => 100 [14] => 100 [vat_total] => 100 [15] => 200 [gross_total] => 200. So you can see that each value is stored twice. As a numeric key and as an associative key. How do I just print it once? – Sw1sh Jun 12 '13 at 13:27
  • If you are getting $total_columns from mysql using mysql functions, you should not use `mysql_fetch_array` (both numeric and associative), but use `mysql_fetch_assoc` for associative or `mysql_fetch_row` for numeric. But if you are realy using `mysql_` functions, see http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php – Hugo Delsing Jun 12 '13 at 13:28

5 Answers5

2

I guess your array comes from a mysql record? If so, then use mysql_fetch_assoc there!

mysql_fetch_array would output => 
array
(
   [0] => "1"
   "foo" => "1"
   [1] => "2"
   "bar" => "2"
)


mysql_fetch_assoc outputs =>
array
(
   "foo" => "1"
   "bar" => "2"
)

This is probably, where your double entries come from. If so, see the docs here

Yami
  • 1,405
  • 1
  • 11
  • 16
0

1) Remove the double keys from the $total_columns in the first place.

2) Check if key is string or integer.

foreach($total_columns as $key => $value){
    if(gettype($key) == "integer"){
    ...
    }
}

3) See array_unique from http://php.net/manual/en/function.array-unique.php

Tauri28
  • 888
  • 1
  • 18
  • 30
0

Well if you just want to make your code work and don't care about why it doesn't try this:

    for($i=0;$i<sizeof($total_columns);$i++)
    {
        echo "<td><b>{$total_columns[i]}</b></td>";
    }
Damarawy
  • 21
  • 1
  • 8
0
print_r($total_columns); 

Result:

[13] => 100 [goods_total] => 100 [14] => 100 [vat_total] => 100 [15] => 200 [gross_total] => 200

It's obvious that you get duplicate values when you try to print them using foreach.

It would be great if you can investigate not to have duplicate values in $total_columns. Still can't understand where do you get them.

let's know the origin of it.

thanks

Harsha
  • 818
  • 11
  • 10
0

Or just read the manual for mysql_fetch_array() and actually use the second parameter correctly (default: MYSQL_BOTH / your choice: MYSQL_ASSOC).

Honk der Hase
  • 2,459
  • 1
  • 14
  • 26