w3resource

PHP Array Exercises : Check whether all array values are strings or not


46. Check if All Array Values Are Strings

Write a PHP function to check whether all array values are strings or not.

Sample Solution:

PHP Code:

<?php
// Function to check if all elements in an array are strings
function check_strings_in_array($arr) 
{
    // Use array_map to check if each element is a string, then sum the results
    // If the sum is equal to the total count of elements, it means all elements are strings
    return array_sum(array_map('is_string', $arr)) == count($arr);
}

// Test arrays
$arr1 = array('PHP', 'JS', 'Python');
$arr2 = array('SQL', 200, 'MySQL');

// Check and display the result for $arr1
var_dump(check_strings_in_array($arr1));

// Check and display the result for $arr2
var_dump(check_strings_in_array($arr2));

?>

Output:

bool(true)                                                  
bool(false)

Flowchart:

Flowchart: PHP - Check whether all array values are strings or not

For more Practice: Solve these Related Problems:

  • Write a PHP function to verify that every element in an array is a string, returning a boolean result.
  • Write a PHP script to iterate over an array and check the type of each element, outputting false immediately if a non-string is detected.
  • Write a PHP program to filter an array for strings and then compare the count with the original array size to verify all values are strings.
  • Write a PHP script that uses array_filter to remove non-string elements and then compares the filtered array with the original.

Go to:


PREV :Multi-Dimensional Array Difference using array_udiff.
NEXT : Get an Array with First Key and Value.

PHP Code Editor:



Contribute your code and comments through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.