给定一个数组$arr = [23,3,45,6,78,8,34],筛选其偶数成员组成新的数组返回,请封装函数
<?php
// 给定一个数组
$arr = [23,3,45,6,78,8,34];
// 封装函数
function grouping(array $arr): array {
// 先声明一个新数组
$newArr = [];
for($i = 0; $i < count($arr); $i++) {
if($arr[$i] % 2 == 0){
$newArr[] = $arr[$i];
}
}
return $newArr;
}
$return = grouping($arr);
var_dump($return);
?>
返回的结果
尝试实现简单的计算器功能,语言不限制。
<?php
error_reporting(E_ALL & ~E_NOTICE);
if($_POST['button']):
if($_POST["choice"] == "/" && $_POST["num2"] == 0 || $_POST["choice"] == "%" && $_POST["num2"] == 0):
echo "除数不能为0";
endif;
endif;
?>
<h2>加减乘除计算器</h2>
<form action="" method="POST">
<input type="number" name="num1" id="num1" required value="<?=$_POST['num1']?>">
<select name="choice" id="choice">
<option value="">--请选择--</option>
<option value="+" <?=$_POST["choice"] == "+" ? "selected" : "" ?>>+</option>
<option value="-" <?=$_POST["choice"] == "-" ? "selected" : "" ?>>-</option>
<option value="*" <?=$_POST["choice"] == "*" ? "selected" : "" ?>>*</option>
<option value="/" <?=$_POST["choice"] == "/" ? "selected" : "" ?>>/</option>
<option value="%" <?=$_POST["choice"] == "%" ? "selected" : "" ?>>%</option>
</select>
<input type="number" name="num2" id="num2" required value="<?=$_POST['num2']?>">
<input type="submit" value="等于" name="button">
</form>
<?php
if(isset($_POST['button'])):
switch($_POST['choice']){
case "+":
$sum = (int)$_POST['num1'] + (int)$_POST['num2'];break;
case "-":
$sum = (int)$_POST['num1'] - (int)$_POST['num2'];break;
case "*":
$sum = (int)$_POST['num1'] * (int)$_POST['num2'];break;
case "/":
$sum = (int)$_POST['num1'] / (int)$_POST['num2'];break;
case "%":
$sum = (int)$_POST['num1'] % (int)$_POST['num2'];break;
}
echo "<span style='color:green;'>{$sum}</span>";
endif;
?>