0

I have this array. How do I remove all those elements which are present in another array i.e. $remove and re-index the final array starting from 1 not 0?

  $info =  array(
    '1' => array('name' => 'abc', 'marks' => '56'),
    '2' => array('name' => 'def', 'marks' => '85'),
    '3' => array('name' => 'ghi', 'marks' => '99'),
    '4' => array('name' => 'jkl', 'marks' => '73'),
    '5' => array('name' => 'mno', 'marks' => '59')
  );
  $remove = array(1,3);

Desired Output:

  $info =  array(
    '1' => array('name' => 'def', 'marks' => '85'),
    '2' => array('name' => 'jkl', 'marks' => '73'),
    '3' => array('name' => 'mno', 'marks' => '59')
  );

So far I've tried these two methods. Nothing worked for me.

  if (($key = array_search(remove[0], $info))) {
    unset($info[$key]);
    $info = array_values($info);
  }

And

  $result = array_diff($info, $remove);
1
  • Do you need to keep the array as an associated array like that with specified keys? Commented May 1, 2013 at 22:02

2 Answers 2

1

Something like this will work:

$result = array_diff_key( $info, array_flip( $remove));

This array_flip()s your $remove array so the keys become the values and the values becomes the keys. Then, we do a difference against the keys with array_diff_key() of both arrays, to get this result:

Array
(
    [2] => Array
        (
            [name] => def
            [marks] => 85
        )

    [4] => Array
        (
            [name] => jkl
            [marks] => 73
        )

    [5] => Array
        (
            [name] => mno
            [marks] => 59
        )

)

Finally, to yield your exact output, you can reindex your array by passing it through array_values(), but this will yield sequential indexes starting at zero, not one:

$result = array_values( array_diff_key( $info, array_flip( $remove)));

If you really need indexes to start at one, you will need a combination of array_combine() and range():

$result = array_diff_key( $info, array_flip( $remove));
$result = array_combine( range( 1, count( $result)), $result);
Sign up to request clarification or add additional context in comments.

1 Comment

And then re-index the keys (starting from 1 somehow) and you're done ;)
0

What about using array_diff function?

Example

$array1 = array("a" => "green", "red", "blue", "red");
$array2 = array("b" => "green", "yellow", "red");
$result = array_diff($array1, $array2);
print_r($result);

this will output

Array
(
    [1] => blue
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.