user5423926
user5423926

Reputation:

How to get last array index inside foreach iteration?

I've found some similar question on StackOverflow, but my problem is different. I'll try to explain more clear possible. First of all the array structure: $appointment

Array ( 
  [id_users_provider] => 85  
  [start_datetime] => 2015-11-15 17:15:00  
  [end_datetime] => 2015-11-15 17:15:00  
  [notes] =>  
  [is_unavailable] =>  
  [id_users_customer] => 87  
  [id_services] => 15 
)
Array (  
  [id_users_provider] => 85  
  [start_datetime] => 2015-11-15 17:15:00  
  [end_datetime] => 2015-11-15 17:15:00  
  [notes] =>  
  [is_unavailable] =>  
  [id_users_customer] => 87  
  [id_services] => 13  
)

How you can see I've two array included in the $appointment variable. Now I want get the end of the last array, in this case the array with id_services: 13. I actually execute an iteration through the appointment['id_services']. Like this:

foreach($appointment['id_services'] as $services)
{
   print_r(end($appointment));
}

but this return me:

15
13

and this is wrong, 'cause I want get only 13 in this case. How I can do that? The main problem is to check inside the foreach loop if the actual $services is the last key of the last array inside the foreach loop.

Upvotes: 0

Views: 82

Answers (2)

Shujaat
Shujaat

Reputation: 691

Your foreach loop is wrong....

Two easy ways to do it...

// using count (not recommended)
echo $appointment[count($appointment)-1]['id_services'];


//using end
echo end($appointment)['id_services'];

based on your comments you might be trying to do this (which i fail to understand why)

$last_appointment = end($appointment);
echo end($last_appointment);

A fix of your code

//not recommended!!
foreach(end($appointment) as $services)
{
   print_r(end($services));
}

Upvotes: 1

hijarian
hijarian

Reputation: 2228

Man, why not just end($appointment)['id_services']? Why do you need a foreach in this case?

$last_appointment = end($appointment);
$id_services = $last_appointment['id_services'];
$id_services === 13; // true

Upvotes: 4

Related Questions