Comparing array elements

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
swendingo
Forum Newbie
Posts: 2
Joined: Wed Mar 10, 2004 11:05 pm

Comparing array elements

Post by swendingo »

I need a function that compares the elements of an array and returns true if all elements are = and false if not.

I am not getting very far trying to write it. does one already exist?
Illusionist
Forum Regular
Posts: 903
Joined: Mon Jan 12, 2004 9:32 pm

Post by Illusionist »

uhh.. maybe you could use ==??

Code: Select all

<?
$arr1 = array('1','2','3');
$arr2 = array('1','2','2'); //change the second 2 to a 3 and it will echo equal!
if ($arr1 == $arr2){
	echo "equal!";
}else{
	echo "not equal!";
}
?>
User avatar
markl999
DevNet Resident
Posts: 1972
Joined: Thu Oct 16, 2003 5:49 pm
Location: Manchester (UK)

Post by markl999 »

I think he means, if you have an array, like array('one', 'one', 'one') how to show they are all the same (which they are in this case) or show they are not all the same, array('one', 'one', 'two'). In which case you could do something like

Code: Select all

$array = array('one', 'one', 'one');
$store = array();
foreach($array as $val){
  if(!in_array($val, $store)){
    $store[] = $val;
  }
}
echo (count($store) == 1) ? 'The same' : 'Different';
..but i may have got the wrong end of the stick ;)
swendingo
Forum Newbie
Posts: 2
Joined: Wed Mar 10, 2004 11:05 pm

Post by swendingo »

exactly what I was looking for.


thank you mark
Post Reply