PHP - 查找数组元素是奇数还是偶数

PHP - Find whether an array element is odd or even

我有一系列这样的项目:

$data = array(
            'item1' => array( // is even
                'icon' => 'commenting',
                'content' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. ',
            ), 
            'item2' => array(// is odd
                'icon' => 'sticky-note',
                'content' => 'Debitis id eligendi assumenda, cumque optio veniam eos perferendis molestias explicabo odit',
            ),
            'item3' => array(// is even
                'icon' => 'users',
                'content' => 'Libero, suscipit, quos. Quae praesentium tempore minima quod tempora odio',
            ),
            'item4' => array(// is odd
                'icon' => 'thumbs-o-up',
                'content' => 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. ',
            ),
            'item5' => array(// is even
                'icon' => 'wrench',
                'content' => 'Debitis id eligendi assumenda, cumque optio veniam eos perferendis molestias explicabo odi',
            ),
        );

我想做的是,当我循环遍历数组的元素以输出它们时,检测每个元素是奇数还是偶数,例如:

foreach ($data as $key => $value) {
    echo '<h1>' . $key . '</h1>';
    echo '<p>' . $value['icon'] . '</p>';
    echo '<p>' . $value['content'] . '</p>';
    echo '<p> (Item is odd or even) </p>'; // * Show wheather is odd or even here
}

使用下面的代码,您可以将 $yourNumber 替换为您要检查的变量。 if statement 检查它是否是偶数,如果它是奇数,则 else 将 运行。

<?php
if ($yourNumber % 2 == 0) {
    echo "It is even.";
} else {
    echo "It is odd.";
}
?>

我们使用modulus来检查它是否是偶数。

可以使用下面的代码:

$i = 1;
 foreach ((array) $data as $key => $value) {
    if($i % 2 == 0) $item = 'even';
    else $item = 'odd';
    echo '<h1>' . $key . '</h1>';
    echo '<p>' . $value['icon'] . '</p>';
    echo '<p>' . $value['content'] . '</p>';
    echo '<p> (Item is '.$item.') </p>'; // * Show wheather is odd or even here
    ++$i;
}

只需声明一个计数器并进行迭代。

$counter = 1;
foreach ($data as $key => $value) {
    echo '<h1>' . $key . '</h1>';
    echo '<p>' . $value['icon'] . '</p>';
    echo '<p>' . $value['content'] . '</p>';
    echo '<p> ' . (($counter % 2)? 'odd': 'even') . ' </p>'; // * Show whether the position is odd or even here
    $counter++;
}
$i = 1;
foreach ($data as $key => $value) {
    echo '<h1>' . $key . '</h1>';
    echo '<p>' . $value['icon'] . '</p>';
    echo '<p>' . $value['content'] . '</p>';
    echo '<p> ' . (($i % 2)? 'odd': 'even') . ' </p>'; // * Show wheather is odd or even here
    $i++;
}

您可以使用计数器、取模运算符和数组将字符串映射到结果:

$map=['This item is: Even','Whilst this one is: Odd'];
$i=1;
foreach ($data as $key => $value): $i++;?>
    <h1> <?= $key;?> </h1>
    <p> <?= $value['icon'];?> </p>
    <p> <?= $value['content'];?> </p>
    <p> <?= $map[$i % 2];?> </p>
<?php endforeach;?>