Home  >  Article  >  Backend Development  >  How to determine whether an array element is a number in php

How to determine whether an array element is a number in php

青灯夜游
青灯夜游Original
2022-05-12 12:17:272714browse

Judgment method: 1. Use foreach loop to traverse the array, the syntax is "foreach ($arr as $v){}"; 2. In the loop body, use is_numeric() to determine whether the array element is a number, the syntax "if(is_numeric($v)){echo "$v is a number";}".

How to determine whether an array element is a number in php

The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer

How does php determine the array? Whether the element is a number

1. Use foreach loop to traverse the array

foreach is a statement specially designed for traversing the array. Commonly used methods provide great convenience in traversing arrays; after PHP5, objects can also be traversed (foreach can only be applied to arrays and objects).

The foreach statement traverses the array regardless of the array subscript, and can be used for discontinuous index arrays and associative arrays with strings as subscripts.

Syntax:

foreach ($array as $value){
    语句块;
}
  • Traverse the given $array array and assign the value of the current array to $value in each loop.

#2. In the loop body, use the is_numeric() function to determine whether the array element $value is a number

is_numeric() function is used Detects whether a variable is a number or a string of numbers.

If the specified variable is a number or numeric string, it returns TRUE, otherwise it returns FALSE. Note that floating point type returns 1, which is TRUE.

Example:

<?php
header(&#39;content-type:text/html;charset=utf-8&#39;);   
$arr = ["q","3",1,2,"34",TRUE,null,4];
foreach($arr as $v){
	if(is_numeric($v)){
		echo "数组元素 $v 是 数字<br>";
	}
}
?>

How to determine whether an array element is a number in php

Recommended learning: "PHP Video Tutorial"

The above is the detailed content of How to determine whether an array element is a number 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