问题
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