Rip Hunter
Rip Hunter

Reputation: 97

Remove certain indexes from 2d array PHP

I have an array like this:

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => Firstname one
            [2] => Lastname one
        )

    [1] => Array
        (
            [0] => 2
            [1] => Firstname two
            [2] => Lastname two
        )

    [2] => Array
        (
            [0] => 3
            [1] => Firstname three
            [2] => Lastname three
        )
)

Now, I would like to remove the entire index 1, i.e., all the firstname's from the array. I was planning on using array_splice by looping through the entire array and removing its index 1. But is there a better way. (I want the re-indexing after deletion of elements.)

Upvotes: 2

Views: 113

Answers (4)

Kuldeep
Kuldeep

Reputation: 200

foreach($array as $k=>$v)
{
    unset($array[$k][1]); /// Chnage the key of array which you want to remove
}

Upvotes: -1

Ravi Hirani
Ravi Hirani

Reputation: 6539

You should use array_map

$input_array = [[1,'Firstname one','Lastname one'],
                [2,'Firstname two','Lastname two'],
                [3,'Firstname three','Lastname three']];

$resultArray = array_map(function($record) { 
  return [$record[0], $record[2]]; // add your desired records
}, $input_array);

echo '<pre>'; print_r($resultArray);

output:-

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => Lastname one
        )

    [1] => Array
        (
            [0] => 2
            [1] => Lastname two
        )

    [2] => Array
        (
            [0] => 3
            [1] => Lastname three
        )

)

Upvotes: 1

Brijal Savaliya
Brijal Savaliya

Reputation: 1091

You can also use array_slice function like

foreach($array as $k=>$v)
{
    array_splice($v, 1,1);
    $array[$k] = $v;
}

OUTPUT :

Array
(
    [0] => Array
        (
            [0] => 1
            [1] => Lastname one
        )

    [1] => Array
        (
            [0] => 1
            [1] => Lastname two
        )

    [2] => Array
        (
            [0] => 1
            [1] => Lastname three
        )

)

Upvotes: 1

nospor
nospor

Reputation: 4220

$yourarray = array_map(function($el) {
  unset($el[1]); //remove index 1
  return array_values($el); //return and reindex
}, $yourarray);

Upvotes: 1

Related Questions