sandeep
sandeep

Reputation: 375

How to print only index of an array

Using select query am select some data from database.

i fetched data using while loop.

while($row=mysql_fetch_array($query1))
 {

}

now i want to print only index of $row.

i tried to print using following statements but it prints index and value(Key==>Value)

foreach ($row as $key => $value) {
    echo $key ;
}

and i tried array_keys() also bt it is also not helpful to me.

echo implode(array_keys($row));

please help to get out this.

i need to print only index.

Upvotes: 1

Views: 542

Answers (4)

aconrad
aconrad

Reputation: 586

$query1 from while($row=mysql_fetch_array($query1)) should be the result from

$query1 = mysql_result("SELECT * FROM table");
//then
while($row=mysql_fetch_array($query1))

To get only the keys use mysql_fetch_row

$query = "SELECT fields FROM table";
$result = mysql_query($query);
while ($row = mysql_fetch_row($result)) {
  print_r(array_keys($row));
}

Upvotes: 0

Amal Murali
Amal Murali

Reputation: 76636

The $row variable in your while loop gets overwritten on each iteration, so the foreach won't work as you expect it to.

Store each $row in an array, like so:

$arr = array();
while($row=mysql_fetch_array($query1)) {
    $arr[] = $row;
}

Now, to print the array keys, you can use a simple implode():

echo implode(', ', array_keys($arr));

Upvotes: 0

jeroen
jeroen

Reputation: 91762

You are fetching the results row as both associative array and a numeric array (the default), see the manual on mysql_fetch_array.

If you need just the numeric array, use:

while($row=mysql_fetch_array($query1, MYSQL_NUM))

By the way, you should switch to PDO or mysqli as the mysql_* functions are deprecated.

Upvotes: 2

Kumar V
Kumar V

Reputation: 8830

You should pass separator(glue text) in Implode function.

For comma separated array keys, you can use below code.

echo implode(",",array_keys($row));

Upvotes: 0

Related Questions