一.将数组的偶数去出, 二.尝试实现计算器功能
一.将一个数组中的偶数取出
方法一 用过滤器的方法
<?php
$arr = [3,5,6,9,15,18,22];
function demo($sum)
{
return !($sum % 2); //声明一个函数,返回取余等于零的为ture
}
$sum1= array_filter($arr,'demo');//将数组中返回为ture的保存到一个新数组中
var_dump($sum1);
方法二 用数组遍历的方法
<?php
$arr = [12,15,18,21,26,30,33,46];
function arr1($number)
{
$arrDouble=[];
foreach($number as $arr2)
{
//将数组中的成员,取余为0为FLASE,然后去反为TRUE,返回为TURE的成员通过入列的方式传到一个新数组中
if (!($arr2 % 2)) array_push($arrDouble,$arr2);
}
return $arrDouble;
//函数返回一个装有偶数的新数组
}
print_r(arr1($arr));
二.尝试实现一个计算器功能
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>尝试实现一个计算机功能</title>
</head>
<?php
$error="";
$num1 = $_POST["num1"] ?? "";
$num2 = $_POST["num2"] ?? "";
$operator = $_POST["operator"] ?? "";
if(isset( $_POST["sub"])){
if($num1 == ""){
$error .= "请输入第一个数据";
}elseif(!is_numeric($num1)){
$error .= "必须是数字";
}
if($num2 == ""){
$error .= "请输入第二个数据";
}elseif(!is_numeric($num2)){
$error .= "必须为数字";
}
if(($operator == '/' || $operator == '%') && $num2 == 0)
{
$error .= "被除数不能为0";
}
}
?>
<body>
<table align="center" border="1" width="600" >
<caption><h2>计算器</h2></caption>
<form action=""method="post">
<tr>
<td>
<input type="text" name="num1" value="<?php echo $num1 ?>">
</td>
<td>
<select name="operator">
<option value="+" <?php if($operator == "+") echo "selected"?>>+</option>
<option value="-" <?php if($operator == "-") echo "selected"?>>-</option>
<option value="*" <?php if($operator == "*") echo "selected"?>>*</option>
<option value="/" <?php if($operator == "/") echo "selected"?>>/</option>
<option value="%" <?php if($operator == "%") echo "selected"?>>%</option>
</select>
</td>
<td>
<input type="text" name = "num2" value="<?php echo $num2 ?>" >
</td>
<td>
<input type="submit" name="sub" value="计算">
</td>
</tr>
<?php
if(isset($_POST["sub"])){
echo '<tr><td colspan = "5" align ="center">';
if(empty($error)){
$sum = 0;
switch($operator){
case "+":
$sum = $num1 + $num2 ;
break;
case "-":
$sum = $num1 - $num2 ;
break;
case "*":
$sum = $num1 * $num2 ;
break;
case "/":
$sum = $num1 / $num2;
break;
case "%":
$sum = $num1 % $num2;
break;
}
echo "结果: {$num1} {$operator} {$num2} = {$sum} ";
}else{ echo $error;}
echo '</td></tr>';
}
?>
</form>
</table>
</body>
</html>