Voting

: six minus zero?
(Example: nine)

The Note You're Voting On

biziclop
2 years ago
Here is another function for checking if two variables refer to each other.
The function by BenBE works properly, but it's very long and maybe slow.
This is a shorter, faster and hopefully bug-free alternative.
Works at least from PHP 4.3.0 to 8.3.4: https://3v4l.org/5JNSl

<?php

function is_same_ref( & $a, & $b ){
  // Save original values
  $ori_a = $a;
  $ori_b = $b;
  // Give them different values
  $a = 1;
  $b = 2;
  // Compare them, if they're equal, they are references to each other
  $eq = $a === $b;
  // Restore original values
  $a = $ori_a;
  $b = $ori_b;
  return $eq;
}

$a = array(1,2);
$b =& $a;
$c =& $a;  // to check for side effects
var_dump( is_same_ref( $a, $b ));
// bool(true)

$a[] = 3;
$b[] = 4;
// After juggling our array in various ways inside is_same_ref(),
// all three variables still refer to the very same array:
var_dump( implode( $a ), implode( $b ), implode( $c ));
// string(4) "3456"
// string(4) "3456"
// string(4) "3456"
?>

<< Back to user notes page

To Top