开发者

array key initial value

i want to set my array key initial value to a certain number. here is what i have:

$tickets=array();
array_push($tickets,"10","20","TBD")

for($i=3; $i<20; $i++)

i want my array initial value to start at 3 not 开发者_JAVA百科0.

any ideas


Set your first value manually with $tickets[3]=$value and PHP will start putting $tickets[] at the next index (4, then 5, etc).


If you're initializing $tickets right there why not use an array literal?

$tickets=array(3=>10, 4=>20, 5=>'TBD');
print_r($tickets);

prints

Array
(
    [3] => 10
    [4] => 20
    [5] => TBD
)

edit and btw: This also works with variables in both places, the key and the value. Therefore

$x = 5;
$y = 'TBD';
$tickets=array(3=>10, 4=>20, $x=>$y);
print_r($tickets);

has the same output as well as

$tickets=array( /* initial index here */ 3=>10, 20, 'TDB');
print_r($tickets);


Set $start_key to 3, and use range() to create the set of keys. Use array_combine() to combine into the array set up how you want:

$tickets = array();
array_push($tickets,"10","20","TBD");
print_r($tickets);
// This is the zero-indexed array that occurs by default:
// Array
// (
//     [0] => 10
//     [1] => 20
//     [2] => TBD
// )

$start_key = 3;
$tickets = array_combine(range($start_key,count($tickets)+($start_key-1)), $tickets);
print_r($tickets);

// Now you have an array whose keys start at 3:
// Array
// (
//     [3] => 10
//     [4] => 20
//     [5] => TBD
// )


Does this work?

$tickets = array();
for ($i=3; $i<20; $i++) {
  $tickets[$i] = 'TBD';
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜