根据顺序计算下一个变量名称的最干净的方法


Cleanest way of working out next variable name based on sequential order?

希望我的标题能解释清楚!以下是更多详细信息:

我正在创建一个数组,其中存储密钥&他们的价值观。例如

test1 = hello
test2 = world
test3 = foo

计算下一把钥匙的最干净的方法是什么?假设我知道第一部分是"测试",但我不知道最高值的数字是什么。显然,在这种情况下,我希望它被称为"测试4"。

在下面的例子中,我希望下一个键是"test46",因为它是下一个最高值:

test6 = blah
test45 = boo
test23 = far

听起来应该使用一个带有数字索引的数组。

但是,您可以使用这样的代码。。。

$arr = array('test6', 'test45', 'test23');
$max = 0;
foreach($arr as $value) {
    $number = filter_var($value, FILTER_SANITIZE_NUMBER_INT);
    $max = max($max, $number);
}
$newKey = 'test' . ++$max; // string(6) "test46"

CodePad。

在不使用循环的情况下实现@alex-answer:

$arr = array('test6', 'test45', 'test23');
$max = max(filter_var_array($arr, FILTER_SANITIZE_NUMBER_INT));
$newKey = 'test' . ++$max; // string(6) "test46"

CodePad

此数据结构最好存储为数组。

$test = array();
$test[] = 'hello';
$test[] = 'world';
$test[] = 'foo';

然后,您不需要知道添加新项的最高数字,只需使用空括号语法(如上所示)将项添加到数组的末尾即可。

然后,您可以访问PHP提供的大量数组函数来处理数据:http://php.net/manual/en/ref.array.php

当你想从数组中获得项目43时,使用:

echo $test[42];

数组是从0而不是1开始计数的,因此项目43的索引为42。

你用它做什么?如果必须对数组进行编号,只需使用一个简单的数字索引数组,如果需要显示为"test1",只需在键前加上"test"即可:

<?php
$array = array(
    6 => 'blah',
    45 => 'boo',
    23 => 'bar'
);
$array[] = 'new';
echo $array[46] . "'n"; // this is 'new'
foreach( $array as $key => $value ) {
    echo "test$key = $value<br />'n"; // test6 = blah
}