-2

I have the following scenario:

  • Array with multiple waypoints
  • Want a new variable for every waypoint
  • Number of waypoints is not fixed

The array stores the address data for the waypoint like street, number, zip, town etc.

I can loop and print the output of the array in foreach loop like:

foreach ($waypoints as $waypoint) {
  echo $waypoint->street
  echo $waypoint->nb
  echo $waypoint->zip
  echo $waypoint->town
}

What I'm trying to do is, to get a new variable for each waypoint. E.g:

$wp1 = Data from waypoint 1
$wp2 = Data from waypoint 2

What I have tried:

$waypointCount = count($waypoints);    

for ($i = 1; $i < $waypointCount; $i++) {
  $wp[$i] = $waypoints->street.' '.$waypoints->nb.' '.$waypoints->zip.' '.$waypoints->town.' '.$waypoints->state;
}

My idea was to count the number of waypoints, set a new variable for each waypoint number and store the corresponding waypointdata in the new variable. I'm kinda stuck on how to create the $wp[i] variables and assign the data to it. Does it need to be a combination with a for and a foreach loop?

Looking for some help to get me on the right direction. Thanks!

1
  • 3
    …why tho…?! You already have an array of waypoints. You can access it as $waypoints[0] etc. What's the advantage of extracting that to individual variables?! (Hint: there is none.) Commented Jul 29, 2020 at 14:25

1 Answer 1

0

It looks like you need to access the correct index of your $waypoints array in your loop. Also, make sure you start your loop with $i = 0 or else you'll skip the first element.

$waypointCount = count($waypoints);    

for ($i = 0; $i < $waypointCount; $i++) {
    $wp[$i] = $waypoints[$i]->street.' '.$waypoints[$i]->nb.' '.$waypoints[$i]->zip.' '.$waypoints[$i]->town.' '.$waypoints[$i]->state;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Totally missed the index there, now it works as expected. Thanks!
@InsaneTeddy Note that you're not creating variables $wp1 etc. with this; you're creating an array $wp.
Yes, noticed that. But helped alot to solve my problem. Thank you for the replies.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.