2018年05月23日
foreachのループを抜ける方法(ループの最初の1つだけ取得する方法)

使い勝手が良くて便利なforeachでのループ処理。条件によっては、ループさぜずに(最初の1つだけを取得した限りで)処理を中断させたいケースがあるかもしれない。
以下のように「endforeach」の直前にbreakを入れてあげればOK。
<?php $images = get_field('xxxxxxxxxx');?>
<?php if($images):?>
<?php foreach($images as $image):?>
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>">
<?php break;?>
<?php endforeach;?>
<?php endif; ?>