3
$almostallTech=array();
$almostallTech[]="no";
$almostallTech[]="no";
$almostallTech[]="yes";
$almostallTech[]="yes";
$almostallTech[]="no";
$almostallTech[]="yes";

$almostallTech=array_unique($almostallTech);
printf("size of array: %d<br/>", sizeof($almostallTech));

for ($x = 0; $x < (sizeof($almostallTech)); $x++) {
    printf("%s", $almostallTech[$x]);
}

After calling the unique method, it returns the size is 2 - which is correct. However the for loop is giving an undefined offset error.

Upon further checking, if I print out:

printf("%s", $almostallTech[0]); - I get no
printf("%s", $almostallTech[2]); - I get yes
printf("%s", $almostallTech[1]); - undefined offset error

So the unique function is removing duplicates but keeping the same index of the former array - which is how it works. This should be simple but can't figure out how to remove the empty or more specifically undefined indexes. Tried the array_filter but still not working. Any suggestions?

What I want is after calling the array_unique method, the duplicates are removed but new indexes should apply. i.e.: I want $almostallTech[0] to contain "no" I want $almostallTech[1] to contain "yes"

2
  • What is your expected array result ? It looks normal as you used array_unique(). Read the manual: php.net/function.array-unique Commented Dec 27, 2013 at 8:37
  • array_values() would be useful to you. check this link php.net/array_values Commented Dec 27, 2013 at 8:51

2 Answers 2

8

Because array_unique() does not re-index the array. You'll have to re-index the array numerically, using array_values() or other similar functions:

$almostallTech = array_values($almostallTech);
Sign up to request clarification or add additional context in comments.

Comments

1

Try

 $almostallTech = array_values(array_flip(array_flip($almostallTech)));

Using array_flip keys from array become values and values from array become keys. Thus you could remove the duplicates but still the indexes would be the same. Now you could use array_values function which returns all the values of the array.

6 Comments

Why is that necessary? Hate to ask, but what do you think array_flip does?
In array same keys doesn't exist together,i think you know that.
So what? Now $almostallTech will be an array of keys, not values -- that's not required. See demo.
Oh Sorry man forgot one array_flip. i was also trying to set the demo.
array_flip(array_flip($arr)) is the same as array_values($arr) --Why is array_flip() necessary? You're flipping the array multiple times only to come back to the original state? The array_flip calls are superfluous.
|

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.