Splitting up a thread

Renegade's picture

He has: 3,022 posts

Joined: Oct 2002

Hey guys,

How do you go about splitting up an array?
For example, say you have this:

<?php
$array
= array(
\
"apple\",
\"banana\",
\"coconut\",
\"duran\",
\"elephant\",
\"fire\",
\"gauze\"
);
?>

and you want to keep to only five (first or last, can't decide yet):

<?php
$array
= array(
\
"apple\",
\"banana\",
\"coconut\",
\"duran\",
\"elephant\"
);
?>

or

<?php
$array
= array(
\
"coconut\",
\"duran\",
\"elephant\",
\"fire\",
\"gauze\"
);
?>

Renegade's picture

He has: 3,022 posts

Joined: Oct 2002

Not really, it seems to me that the array content still stays, I want it to be gone completely

s0da's picture

He has: 157 posts

Joined: Mar 2004

maybe this would be more simpler to answer if we actually knew what you were doing. i don't see how the slice function didn't work. :/

Abhishek Reddy's picture

He has: 3,348 posts

Joined: Jul 2001

_slice() returns a range, but doesn't delete the others. unset($arr[$key]) should remove the element, I think.

s0da's picture

He has: 157 posts

Joined: Mar 2004

yeah but he'd have to go in and do unset() for all the keys he doesn't want. it would be better if we knew what he was actually going to do with the array.

s0da's picture

He has: 157 posts

Joined: Mar 2004

<?php
$crazy
= array(
\
"apple\",
\"banana\",
\"coconut\",
\"duran\",
\"elephant\",
\"fire\",
\"gauze\"
);

for (
$i = 0; $i < count($crazy); $i++)
{
    if (
$i > 4) unset($crazy[$i]);
}

# eh? that takes care of the first 5 you want
?>

not sure if this works Wink haha

Chroder's picture

He has: 91 posts

Joined: Mar 2004

array_slice returns the array, so you could just overwrite the old one with the new one

<?php
$crazy
= array(
\
"apple\",
\"banana\",
\"coconut\",
\"duran\",
\"elephant\",
\"fire\",
\"gauze\"
);

$crazy = array_slice($crazy, 2);
?>

Renegade's picture

He has: 3,022 posts

Joined: Oct 2002

Ah, Chroder, nice, I'll try that sometime.

Thanks for the input guys Laughing out loud

Want to join the discussion? Create an account or log in if you already have one. Joining is fast, free and painless! We’ll even whisk you back here when you’ve finished.