1
$array1 = array(1=>"Band",2=>"Song", 3=>"Release",4=>"Year");
$array2 = array(1=>"Band");
print_r(array_intersect($array1,$array2));

Expected : array(1=>"Band") but i got an empty array();

1
  • 3
    You have a BOM character at the beginning of the first Band. Commented Dec 15, 2022 at 20:48

1 Answer 1

1

@Barmar has already mentioned the cause in his comment. The differences cannot be shown with print_r. var_dump shows a different length for the first element.

$array1 = array(1=>"Band",2=>"Song", 3=>"Release",4=>"Year");
$array2 = array(1=>"Band");

var_dump($array1,$array2);

Output:

array(4) {
  [1]=>
  string(7) "Band"
  [2]=>
  string(4) "Song"
  [3]=>
  string(7) "Release"
  [4]=>
  string(4) "Year"
}
array(1) {
  [1]=>
  string(4) "Band"
}

Removing the BOM before the 'Band' solves the problem. The following line only removes a BOM only if it is at the beginning of the string.

$array1[key($array1)] = preg_replace("~^\xef\xbb\xbf~u","",$array1[key($array1)]);

Try it yourself: https://3v4l.org/NYnPG

I find it commendable that the editor of 3v4l.org also shows the difference.

However, a BOM should always be removed when importing (CSV?)data .

Sign up to request clarification or add additional context in comments.

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.