1

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.

2
  • to the part with the counter: it must be ++$counter; or $counter++; Commented Apr 24, 2012 at 9:38
  • 1
    What is the structuere of your array? Commented Apr 24, 2012 at 9:41

3 Answers 3

2
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;
}
Sign up to request clarification or add additional context in comments.

8 Comments

this works great. just one more thing i would like to know. how can i set the start at 1 and not 0? thanks a lot.
You could skip the first iteration of the array using continue, I'll edit my answer
is there still another way? the first array[0] contains input. in case of using that the input wont be displayed.
Sorry I wrongly assumed you had a numerically indexed array, not really sure why as it wouldn't have made sense. I've updated my answer.
i get the same mistake. it seems like continue easily jumps to the next entry in that array. so the first wont be considered.
|
1
foreach($arr as $key=>$val){
//do something with key and value
}

Comments

0

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*/
 }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.