Jump to content

Two questions about array indexes


galvin

Recommended Posts

I have this simple code below to pull back info from a mysql database and create an array.  I have two questions...

 

1.  The items in this array will automatically have indexes of [0] and [1] and [2] and so on.  If I wanted the first index to be [1] instead of [0], how could I do that?

In other words, I want the first item in the array to have an index of [1] (like regular counting) rather than [0] (programming counting).

 

2.  Each 'answer' actually has its own 'answerid' in the database, which I am bringing back as well with the query.  If I wanted those answerids to be the indexes,  how would I adjust the code below?

 

	
$sql = "SELECT answer, answerid FROM answers
	WHERE quizid = $quizid";
	$createanswerarray = mysql_query($sql, $connection);
		if (!$createanswerarray) { 
		die("Database query failed: " . mysql_error());
		} else {
		$_SESSION['answers']=mysql_fetch_array($createanswerarray);
		} 
} else {

}

 

Link to comment
Share on other sites

For both of those, you will need to renumber your array.  To set the answerid as the index I would recommend you create a new array rather than renumbering, so you don't accidentally clobber something if you have low answerids that match the old array indexes.

Link to comment
Share on other sites

1. don't do that. always know that the first element of an array is key 0. if you need to display 1 for 0, add +1 to the key. but don't change the key; keep consistency.

 

2. create a new array. loop over the query results, assigning $newarray[$answerid] = $answer for each record

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.