Sheju Sathyanesan
Sheju Sathyanesan

Reputation: 7

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

Upvotes: 0

Views: 1341

Answers (2)

AbraCadaver
AbraCadaver

Reputation: 79024

Much simpler:

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

Upvotes: 1

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89639

You don't need to put <?php ... ?> everytime everywhere for each statement. Keep in mind that each time you close with ?> all characters are sent to the client until the next opening <?php, that's why you obtain spaces around each comma:

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

(I changed white-spaces to #, this way you can see characters sent to the client (the browser)).

You can use array_map to "filter" only ID items and implode to join them , then you only need to store the result in a variable ($result here).

<?php
$images = get_field('photogallery');
$result = implode(',', array_map(function ($i) { return $i['ID']; }, $images));
echo $result;
?>

Now you can use $result later everywhere you want.

Upvotes: 3

Related Questions