Php array modulo every second value

杀马特。学长 韩版系。学妹 提交于 2019-12-25 18:42:06

问题


I have a question. I have this array of the alphabet. And every even letter needs to be !$letter, so it needs to echo out !b, !d, !f

I'm unsure how to do this. I've been told to use the modulo, % for this.

But reading a lot about it on the internet and things haven't gotten any clearer for me.

I appreciate anyone that can help me on this matter! Thanks in advance!


回答1:


foreach ($alphabet as $i => $letter) {
    echo (($i % 2) == 1 ? '!' : '') . $letter;
}

$i is the position of the letter in the array; since array indexes start from 0, even letters will have odd indexes.

$i % 2 is 0 when $i is even, 1 when it's odd. This is grade school arithmetic, which should be a prerequisite for a programming career.



来源:https://stackoverflow.com/questions/21483416/php-array-modulo-every-second-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!