0

I have this variable :

$key = 'text1-text2-text3-021-039-947-927-827-927';
$key = explode ('-', $key);

first three of $key ($key[0]...$key[2]) always contains text and it won't be a problem to me. but the rest of it is dynamic.

in that case, the rest of it contains 6 more variables : $key[3]...$key[8] but some other case, it can be 10, 9, 2, etc based on user's input.

now the question is... how to echo each key by using FOREACH loop starting with $key[3]? not $key[0]. thanks.

2
  • 3
    for ($i=3; $i<count($key); ++$i){ }; foreach always starts at the first element. Commented Oct 26, 2012 at 3:58
  • Why not remove the first 3 elements before the foreach? Or use a for loop instead? Commented Oct 26, 2012 at 3:59

5 Answers 5

2

Try like this:

for($i=3; $i<count($key); $i++){
   echo $key[$i];
}
Sign up to request clarification or add additional context in comments.

5 Comments

I would use count outside of the loop so it's not getting called every pass through the loop...
yaa sure, that would be better :).
@frosty Not that it really makes any noticeable difference.
i<count($key) should be $i<count($key).
@NullUserException I agree the difference isn't noticeable in this case, but calculating the count of an array on every pass through the loop isn't necessary. The value of count($key) is not changing, so why not just assign it to a variable outside the loop? Just because there's no noticeable ramifications in a small script doesn't mean it should be done that way. Just my opinion :)
1

Try this code you have the key and value

$key = 'text1-text2-text3-021-039-947-927-827-927';
$key = explode ('-', $key);


foreach ($key as $k=>$val)
{
   if($k>=3)
   {
     echo "key=".$k ."and value=".$val;
     echo '<br />';
   }
}

Comments

0

try this snippet

$isFirst = 1
foreach ($arr as &$value) 
{
    if ($isFirst == 1)
    { 
        $isFirst = 0;
    }
    else
    {
        // do code here
    }
}

why not use For Loop?

for ($i = 1; $i <= 10; $i++){....}

Comments

0
$key = 'text1-text2-text3-021-039-947-927-827-927';
$key = explode ('-', $key);

foreach($key as $count=>$values){
  if($count>=3) {
     echo $values."<br/>";
  }    
}

output=>

021
039
947
927
827
927

Comments

0

This may not be the best answer, but just the heck of it (and because I wanted to provide yet another solution using foreach):

$key = 'text1-text2-text3-021-039-947-927-827-927';
$key = explode ('-', $key);

array_shift($key); //remove first element..
array_shift($key); //remove second element..
array_shift($key); //remove third element..

//there you go..
foreach($key as ..)

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.