How do I remove an array elements from another array?

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);

Answers


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);

Need Your Help

Understanding the exact meaning of the “void” Keyword in C/C++

c++ c

As explained, for example, here, we all know of 3 main uses for the void keyword (more experienced C/C++ programmers can skip to the 4th use):

Expressing byte values > 127 in .Net Strings

c# .net string character-encoding

I'm writing some binary protocol messages in .Net using strings, and it mostly works, except for one particular case.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.