Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

reformatting array keys 1

Status
Not open for further replies.

ChrisMacPherson

Programmer
Jul 3, 2000
157
GB
Hi all,

I am trying to re-set the keys/indexes of an array so that they start from 0 and go up 1,2,3,4 etc. Here's how I want to do it :

the original array looks like this

[0] => apples
[1] => oranges
[2] => pears
[3] => apples
[4] => oranges

then I use the array_unique() method so I remove duplicates.
this makes the array look like this

[2] => pears
[3] => apples
[4] => oranges

Now I want to re-set the indexes/keys so that it looks like this

[0] => pears
[1] => apples
[2] => oranges

It doesn't matter about the order of the values, only the keys. I cant seem to do it. Is there a method that will do this for me, or do I have to write some code for it ?

Thanks for any help

Chris MacPherson
macpweb@hotmail.com
Bring on the new Browza's!!
 
Here, this will do it for you:

[tt]
<?php

$array = array(&quot;apples&quot;,&quot;oranges&quot;,&quot;pears&quot;,&quot;apples&quot;,&quot;oranges&quot;);
$array = array_unique($array);


for ($i=0; $i<count($array); $i++) {
$pos = pos($array);
if ($array[$i] == &quot;&quot;) { // array index does not exist.
$temp = array_splice($array,$i);
}
}


for ($i=0; $i<count($temp); $i++) {
print $temp[$i].&quot;<br>&quot;;
}

?>
[/tt]

Here's what it does:

1. Creates the array.
2. Removes multiple values.
3. Loop through the array and test to see if there are array indexes that do not exist.
4. If so, splice out the rest of the array and place it in $temp.
5. Print out the values of $temp.

Hope this helps.
-Vic vic cherubini
krs-one@cnunited.com
====
Knows: Perl, HTML, JavScript, C/C++, PHP, Flash
====
 
Cool thanks,

That seems to work fine, I had actually tried somthing quite similar, but it didn't work. Can you tell me why you have the pos($array) method in the above code. Do you have to pull the element before testing it's value? That might be where I was going wrong.

Thanks again. Enjoy your Vote Chris MacPherson
macpweb@hotmail.com
Bring on the new Browza's!!
 
Oh, hehe, now I feel embarressed. I was trying some other methods before I got what I was trying, and I was trying to use the pos() function. You can take that out, its just in there from previous attempts at getting this little script to work.

*blushes*

-Vic vic cherubini
krs-one@cnunited.com
====
Knows: Perl, HTML, JavScript, C/C++, PHP, Flash
====
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top