Take the 2-minute tour ×

How can I add an index (1,2,3) to an array like this:

$errors['success'] = false; //0
$errors['#errOne'] = "Enter a valid username"; //1
$errors['#errTwo'] = "Enter a valid email";//2
$errors['#errThree'] = "Enter a valid password";//3
share|improve this question
add comment

2 Answers

up vote 2 down vote accepted

Just use the integer index instead of the string index.

$errors[0] = false;

If your order doesn't matter, it's easier yet to not specify an index, and PHP will push it onto the array.

$errors[] = false;
$errors[] = "Enter a valid username";

Looking at your structure though, I would suggest not keeping such a mix of things in your array. You should have an array for your list of errors, and a separate value for whether or not something was successful. (Is the definition of successful no errors? If so, you can check for that.) Maybe something like this instead?

$status['success'] = false;
$status['errors'] = array();
$status['errors'][] = 'Enter a valid username';
// etc.
share|improve this answer
add comment

If you dont care about elements order:

$errors = array_values($errors);

If you need to specify a some order:

$errors = array(
share|improve this answer
add comment

Your Answer


