views:

52

answers:

4

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 0.

any ideas

A: 

Does this work?

$tickets = array();
for ($i=3; $i<20; $i++) {
  $tickets[$i] = 'TBD';
}
Jansen Price
yup but i want to access the whole aray from 10, etc. where the initial array[3] = 10, but i am not getting it.so array[5]=TBD
Menew
+2  A: 

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

David Souther
As the documentation clearly says: *Syntax `index => values`, separated by commas, define index and values. `index` may be of type string or integer. (...) If index is an integer, **next generated index** will be the biggest integer `index + 1.`* http://php.net/manual/en/function.array.php
Felix Kling
+1  A: 

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);
VolkerK
A: 

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
// )
artlung