0

I'm trying to filter out values by their even index numbers, but it isn't going well. $date is being return as the full array but with the last index missing. Is this because I'm using explode()?

Here's my code;

$route = "Dest A:0900:Dest B:0930:Dest C:1000";

$route_array = explode(":", $route);

foreach($route_array as $key){
    if(!($key & 1)){
        $date[] .= $key;
    }
}
return $date;
2
  • I assume that the reason is because you only want the times? Commented Nov 8, 2012 at 13:52
  • Well, ideally I'd like to seperate the destination from the times. I actually think I've figured out how to do it now that I've asked! Will post shortly. Maybe there's a more simple way... Commented Nov 8, 2012 at 13:53

3 Answers 3

1

your loop should look like this

foreach($route_array as $k=>$key){
    if(($k+1)%2 == 0){
        $date[] = $key;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

I believe this is the problem:

foreach($route_array as $key)

You call the variable $key, but it will actually contain the value of that array element.

Instead, you should do the following:

foreach($route_array as $key => $value)

An then check wether the $key is odd or even. Now $value will contain either the destination or the time.

1 Comment

Thanks for answering NicNLD. I ended up doing this in my final answer below.
0

Thanks for the answers guys...

Okay, so five minutes later I had a light bulb moment and came up with a solution;

$route = "Dest A:0900:Dest B:0930:Dest C:1000";
$route_array = explode(":", $route);

foreach($route_array as $key => $value){
    if(!($key & 1)){
        $date[] .= $route_array[$key];
    }
}
return $date;

2 Comments

This might work. However, the value of $route_array[$key] is already stored in $value, so why do you look it up again?
Yeah that's true, I've now amended my code to assign $value rather than $route_array[$key]. I'm a bit of a noob with PHP - thanks for the heads up.

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.