";}"."/> ";}".">

Home  >  Article  >  Backend Development  >  How to find the number in an array that is divisible by 3 in php

How to find the number in an array that is divisible by 3 in php

青灯夜游
青灯夜游Original
2022-06-01 12:06:542545browse

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."
";}".

How to find the number in an array that is divisible by 3 in php

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>";
	}
}
?>

How to find the number in an array that is divisible by 3 in php

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn