Jump to content

Recommended Posts

Is there a way to do something like array_pop() where I can specify the key to remove and then it will drop the rest of them down?

 

Like if array contains the following

Key -> Value

0          A

1          B

2          C

3          D

4          E

 

And I remove key 2 it'll be like this

Key -> Value

0          A

1          B

2          D

3          E

 

instead of this

Key  -> Value

0          A

1          B

2          Null

3          D

4          E

Link to comment
https://forums.phpfreaks.com/topic/197131-array-manipulation-question/
Share on other sites

You could also use array_values to reorder the keys, as your example does.

 

I tried to use array_values like this

 

	$arr = array(1,2,3,4,5);
print_r($arr);
unset($arr[2]);
print_r($arr);
array_values($arr);
print_r($arr);

 

but just got this

 

Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 )

Array ( [0] => 1 [1] => 2 [3] => 4 [4] => 5 )

Array ( [0] => 1 [1] => 2 [3] => 4 [4] => 5 )

 

It didn't re-key them for me :/

In my original post I didn't realize that you wanted the keys reset. You can do something like this to get that effect:

 

<?php
$arr = array(
0 => 'A',
1 => 'B',
2 => 'C',
3 => 'D',
4 => 'E'
);

unset($arr[2]);

$new_arr = array_combine(range(0, sizeof($arr) - 1), array_values($arr));

print_r($new_arr);

In my original post I didn't realize that you wanted the keys reset. You can do something like this to get that effect:

 

<?php
$arr = array(
0 => 'A',
1 => 'B',
2 => 'C',
3 => 'D',
4 => 'E'
);

unset($arr[2]);

$new_arr = array_combine(range(0, sizeof($arr) - 1), array_values($arr));

print_r($new_arr);

 

Thank you Alex! Works perfectly :) Gonna have to look into this function. Seems like you are just splitting the array into what was before and what was after and pulling them together. Would this be a bad idea to do on a large SESSION array especially if I am not using any kind of temporary array to store it in? like

 

$_SESSION['results'] = array_combine(range(0, sizeof($_SESSION['results']) - 1), array_values($_SESSION['results']));

 

I couldn't imagine so but I'm just making sure ;) Thanks again tho Alex

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.