user1051322
user1051322

Reputation:

Re-order the array order both key and value

Say I've got an array

[0]=>test
[2]=>example.

I want o/p as

[0]=>test
[1]=>example

In my first array

[1]=>NULL

I've tried to remove this and reorder so, I used array_filter() to remove the null value.

Now, how do I reorder the array?

Upvotes: 1

Views: 95

Answers (4)

Igor Parra
Igor Parra

Reputation: 10348

<?php
$a = array(0 => 1, 1 => null, 2 => 3, 3 => 0);

$r = array_values(
        array_filter($a, function ($elem)
                {
                    if ( ! is_null($elem))
                        return true;
                })
);

// output:

array (
  0 => 1,
  1 => 3,
  2 => 0,
)
?>

NOTE: I am using an anonymous callback function for array_filter. Anonymous callback only works in php 5.3+ and is the appropriate in this case (IMHO). For previous versions of php just define it as normal.

Upvotes: 0

deviousdodo
deviousdodo

Reputation: 9172

If I understand what you need, I think array_values should help (it will return only the values in the array, reindexed from 0):

print_r( array_values($arr) );

Here's an example of this: http://codepad.org/q7dVqyVY

Upvotes: 3

NekaraNef
NekaraNef

Reputation: 207

$Array = array('0'=>'test,', '2'=>'example');
ksort($Array);
$ArrayTMP = array_values($Array);

or

$Array = array('0'=>'test,', '2'=>'example');
ksort($Array);
$ArrayTMP = array_merge ($Array,array());

Credit goes to: http://www.codingforums.com/archive/index.php/t-17794.html.

Upvotes: 0

Sgoettschkes
Sgoettschkes

Reputation: 13189

You might want to use merge:

$newArray = array_merge(array(),$oldArray);

Upvotes: 0

Related Questions