从数组中提取数字

时间:2018-12-30 07:41:24

标签: php arrays

如何仅从数组中提取数字?

$myarray = array("A","B", "2","D");

我想从数组中获取数值(在此示例中为“ 2”)

2 个答案:

答案 0 :(得分:2)

您可以使用is-numericarray-filter(PHP内置函数):

$myarray = array("A", "B", "2", "D", "3");
$b = array_filter($myarray, "is_numeric");

现在$b是一个包含字符串23的数组。

已编辑:关于您的评论:如果您只有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

答案 1 :(得分:0)

<?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);

输出:

float(12.2)