Sheju Sathyanesan Sheju Sathyanesan - 1 month ago 6
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

1102,3380,3348,3354,3355


Please help me.. thanks

Answer

Much simpler:

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