bonny
bonny

Reputation: 3245

output specific array key for each result

i have a search engine for my page. as a result i would like to ouput the array key for each result.

so i have this code:

$results = search($keywords);
$results_num = count($results); //what shows the message how many items were found

if (!empty($errors){
foreach ($results as $result){
    echo "this is result: "
.$result['key'];       //thought would be the solution, its not.
    }
} else {
    foreach ($errors as $error){
        $error;
    }
}

i also tried using a counter like:

$results = search($keywords);
$results_num = count($results); //what shows the message how many items were found
$counter = 0;

if (!empty($errors){
foreach ($results as $result){
    $counter++;
    echo "this is result: "
.$counter;
    }
} else {
    foreach ($errors as $error){
        $error;
    }
}

what doesnt work as i thought and is still not that professional. so if there is someone who could tell me how to solve this i really would appreciate. thanks a lot.

Upvotes: 1

Views: 557

Answers (3)

Er. Anurag Jain
Er. Anurag Jain

Reputation: 1793

Here in code you can check first if $results array is not empty because sometime due to empty $results array foreach generates error

/*Check if $results array is empty or not*/
if(!empty($results)){  
 foreach ($results as $key=>$result){
  /*result you want to show here according conditions*/
 }
}

Upvotes: 0

billyonecan
billyonecan

Reputation: 20270

foreach ($results as $key => $result) {
  echo 'this is result: ' . $key;
}

The current key will be assigned to $key and the value for that property will be assigned to $result

http://php.net/manual/en/control-structures.foreach.php

edit

In response to your comments, I think this is what you're trying to achieve:-

$i=0;
foreach($results as $result) {
  echo 'this is result: ' . ++$i;
}

Upvotes: 2

web2students.com
web2students.com

Reputation: 307

foreach($arr as $key=>$val){
//do something with key and value
}

Upvotes: 1

Related Questions