hi,

i would like to print a specific range of array element using foreach() function.
let say i have this array,

$topic_rel = array(0=>'start', 1, 2, 3, 4=>'four', 5, 6, 7, 8, 
9, 10=>'ten', 12, 13, 14, 15=>'end'):

now how would i print the key and value of an elements from starting key = 5
and upto key = 12, using foreach function?

i know i can do this in for() and while() but i want it to iterate using foreach().

Thank you very in advance.

    Foreach works for every single element, so you should slice array first:

     
     $topic_rel = array(0=>'start', 1, 2, 3, 4=>'four', 5, 6, 7, 8, 
    9, 10=>'ten', 12, 13, 14, 15=>'end');
     print_r($topic_rel);
     echo '<hr />';
     $topic_rel = array_slice($topic_rel, 5, 12-5+1);
     foreach($topic_rel as $key => $value){
     	echo $key + 5 . ' :: ' . $value . '<br />';
     }
    

    Foreach function shouldn't be used that way - it's used to get all elements stored in array.

      I don't think you understood my condition of foreach().

      ok, here is the condition again.

      I want to print the keys from 5 to 12 only...

      thanks again in advance. and not the entire array keys.

        You don't. Not with foreach. Try using [man]for[/man]

          <?php
          $topic_rel = array(0=>'start', 1, 2, 3, 4=>'four', 5, 6, 7, 8, 9, 10=>'ten', 12, 13, 14, 15=>'end');
          foreach($topic_rel as $k=>$v)
          	{
          		if(($k>=5) && ($k<=12))
          			echo($v."<br />");
          	}
          ?>
          

            Why do you need foreach as opposed to for? Foreach will move the array pointer; if you have to reiterate through that same array you will have to use reset() to move it back; you don't have to do that with a for loop.

            Phil

              Write a Reply...