0

This array is being populated with URL's using a for each loop (they are page number URL's)

$pageNumberLinks[] = "<a href= URL_code>".$page_number . "</a>";

I am trying to reference the $page_number variable value in each URL in the array as the foreach loop executes, so I can use an if statement to execute code based on the $page_number value. $PageNumberLinks->page_number is not working. Any advice?

foreach ($pageNumberLinks as $PageNumberLinks) {
    if ($PageNumberLinks->page_number == $z ) {
        // execute code
    } else {
        // execute code
    }
}
3
  • 1
    What if you define $pageNumberLinks[$page_number] = "<a href= URL_code>".$page_number . "</a>"; ? This way, you will be able to loop through the indexes properly. Commented Mar 15, 2014 at 22:06
  • The $page_number variable isn't accessible in the way your are using it. The -> is attempting to access an object property. Unless $PageNumberLinks is an object, then it won't work. Commented Mar 15, 2014 at 22:06
  • Good advice! The code works! But the foreach loop isn't displaying the URL's. It is only displaying numbers. Commented Mar 16, 2014 at 2:29

2 Answers 2

1

Just do:

$pageNumberLinks[$page_number] = "<a href= URL_code>".$page_number . "</a>";

foreach ($pageNumberLinks as $key => $val) {
    if ($key == $z) {
        // execute code
    } else {
        // execute code
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

So basically what @fedorqui said 6 minutes ago in the comments?
@PeeHaa: Yes, basically, except this is an answer not a comment.
Good advice! The code works! But the foreach loop isn't displaying the URL's. It is only displaying numbers.
@DeanOlsen: My foreach doesn't display anything. That should be a trivial exercise depending on what you want to display.
0

You should build your array with proper indexes which will make it easier for you to loop thru:

$pageNumberLinks[$page_number] = "<a href= URL_code>".$page_number . "</a>";

Then you create a loop like

foreach($pageNumberLinks as $pageNumber => $link){    
  if(  $pageNumber === $z ){
    //do code here
  }else{
   //do some code here
  }    
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.