[英]Extract Numbers from Array
How to extract only Numbers from an Array? 如何仅从数组中提取数字?
$myarray = array("A","B", "2","D");
I want to get numeric values ("2" in this example) from an array to a variable 我想从数组到变量获取数值(在此示例中为“ 2”)
You can use is-numeric and array-filter (PHP build-in functions): 您可以使用is-numeric和array-filter (PHP内置函数):
$myarray = array("A", "B", "2", "D", "3");
$b = array_filter($myarray, "is_numeric");
Now $b
is an array containing the strings: 2
and 3
. 现在
$b
是一个包含字符串的数组: 2
和3
。
Edited Regarding your comment: if you have only 1 value and you want to add 10
to it you can do: 编辑关于您的评论:如果您只有1个值,并且想要添加
10
,则可以执行以下操作:
$myarray = array("A", "B", "2", "D");
$b = array_filter($myarray, "is_numeric");
$c = array_values($b); //reset the keys
$finalvalue = $c[0] + 10; // will output 12
<?php
$input = array('A','B', '2.2','D');
foreach($input as $v)
is_numeric($v) && $nums[] = $v;
// Take the first numeric found and add 10.
$result = isset($nums[0]) ? $nums[0] + 10 : null;
var_dump($result);
Output: 输出:
float(12.2)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.