3

I want to check in a single statement, if the contents of array are same or not. This is actually a challenge for me, but I am not able to check for the uniqueness of the values inside an array.

Also I want to make sure that the values are same as, say "S". Example array:

$myArray = array("S", "S", "S");  // true
$myArray = array("S", "S", "s");  // false

Is it possible using a single statement? Thanks in advance.

2
  • Yes, possible with array_count_values. Is this what you are looking for? Commented Jan 28, 2016 at 11:35
  • 2
    There are many ways. i think you did not do any efforts to solve this. Commented Jan 28, 2016 at 11:37

1 Answer 1

2

Yes, possible with array_count_values. Is this what you are looking for?

The function array_count_values() will count the number of unique values in the array. If you get the count of it to be 1, it is then unique like you said.

count(array_count_values($myArray)) == 1

Also, you can check one of the array values to be whatever value you wanted to check.

$myArray[0] == "S"

So combining these two in a single condition:

count(array_count_values($myArray)) == 1 && $myArray[0] == "S"

This will return true or false.

Full Working Code

<?php
    // Let's have two arrays.
    $myArray1 = array("S", "S", "S");  // Should return true
    $myArray2 = array("S", "S", "s");  // Should return false

    // Our function
    function checkArray($theArray, $value) {
      return count(array_count_values($myArray)) == 1 && $myArray[0] == $value;
    }

    // Checks
    checkArray($myArray1, "S"); // true
    checkArray($myArray2, "s"); // false
Sign up to request clarification or add additional context in comments.

6 Comments

This is exactly what I wanted, minus the function. Thanks a lot.
@JohnBlake Woah.. Awesome... Glad to help. Welcome! :)
Why $myArray[1]!? What about arrays containing only one element?
@deceze LoL. My bad. :P Wanted it to be fancy! :P
@bpoiss The idea is to check all elements of array are same. So, if there are no elements, the first condition fails. My code works. :) Basically there should be at least one element to make the array look good. Right?
|

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.