";}"."/> ";}".">
Home > Article > Backend Development > How to find the number in an array that is divisible by 3 in php
Method: 1. Use the foreach statement to loop through the array, with the syntax "foreach($arr as $v){//loop body}"; 2. In the loop body, determine whether the array element "$v" It can be divisible by 3. If so, it will be output. The syntax is "if($v%3==0){echo $v."
";}".
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
php seeks the array Methods that can be divisible by 3
1. Use the foreach statement to loop through the array
foreach ($array as $value){ //循环体语句块; }
Traverse the given $array array, in each In the second loop, the value of the current array is assigned to $value.
2. In the loop body, determine whether the array element $value is divisible by 3. If so, output
if($value%3==0){ echo $value."<br>"; }
Analysis:
can be divisible by 3, in other words, the remainder after dividing by 3 is 0;
Therefore, you can use the % operator to find the remainder, Just use == to determine whether the remainder is equal to 0.
Complete code:
<?php header("Content-type:text/html;charset=utf-8"); $arr=array(2,3,5,6,7,8,9,17,20,12,15,25,24,81); var_dump($arr); foreach($arr as $value){ if($value%3==0){ echo $value."<br>"; } } ?>
Recommended learning: "PHP Video Tutorial"
The above is the detailed content of How to find the number in an array that is divisible by 3 in php. For more information, please follow other related articles on the PHP Chinese website!