Rafff
Rafff

Reputation: 1518

Deleting $key from array cleans the array

The following code uses an array in order to search if an ID in the array matches to $rmid. If true it removes the whole proper key.

$rmid = 1;
$data = $db['refs'];
// remove element
foreach( $data as $k => $v ) {
  if( in_array( $rmid, $v ) ) {
    unset( $data[$k] );
  }
}

Hovewer, if exactly 1 is passed to the $rmid, it deletes all keys from the array! Not the only one with $rmid = 1. What's wrong with my code?

EDIT

Opps. Right after posting I just realized:

if( $rmid == $v['id'] ) {
  unset( $data[$k] );
}

Thank you for your effort!

Upvotes: 0

Views: 39

Answers (1)

t3chguy
t3chguy

Reputation: 1018

Use:

if( in_array( $rmid, $v, true ) ) {

the third parameter enforces a === instead of a ==, 1 evaluates to true but so do most other things, loosely in PHP. [== works for comparing two things of the same type, but when it does type conversion it can have some strange quirks]

Upvotes: 1

Related Questions