Check if all function arguments are equal in PHP

Question: Could this be written better?

private function compareThree($val_1, $val_2, $val_3)
{
    return (($val_1 == $val_2) && ($val_1 == $val_3) && ($val_2 == $val_1) && ($val_2 == $val_3) && ($val_3 == $val_2) && ($val_3 == $val_1));
}

Short Answer: Yes! That’s horrible and makes my eyes bleed.

Long Answer: Why compare only three? Why not build a function that compares a infitine number of arguments and check if they are all equal. Here’s my solution:

function compareAllTheArguments()
{
    return count(array_unique(func_get_args())) === 1;
}

Explanation:

func_get_args() // Get all function arguments in array list

 array_unique() // Removes duplicate values from an array

count() // Well, yeah, returns the number of elements in a array

Knowing this first we get all the arguments in the function then remove all the duplicates and if it’s only one left that means all elements are equal.

  1. seriously , pick up a logic book.
    ((a == b) && (b == c)) -> (a == c) : true

Leave a Comment

NOTE - You can use these HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>