Sheju Sathyanesan Sheju Sathyanesan - 1 year ago 53
PHP Question

Getting the value outside the foreach php loop

Here is the code used to get the ids of a images in a gallery

<?php $images = get_field('photogallery');?>

<?php foreach( $images as $image ): ?>
<?php echo $image['ID']; ?>
<?php echo ','; ?>
<?php endforeach; ?>

I get the output

1102 , 3380 , 3348 , 3354 , 3355 ,

I would like to get this outside the loop because the result must be used in other shortcode also I see there is a whitespace after every number.

the result must be


Please help me.. thanks

Answer Source

Much simpler:

<?php echo implode(',' array_column($images, 'ID')); ?>
  • extract the ID values using array_column()
  • implode() those array values using a comma