2

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

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

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. php.net/manual/en/function.array.php
1

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

Comments

1

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

Comments

0

Does this work?

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

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.