0

I have tried out with the google and tried myself to get done for the below functionality. I need a function that will validate each array element whether it is scalar or not. So i wrote a simple function that will iterate each element of the array and checks for scalar or not.

But the real requirement, the array could be a multi dimentional array. So i have modified the array and called the function recursively as below, But it will not go-through all elements in the array.

function validate_scalar($params)
{
    foreach ($params as $key => $arg)
    {
        if (is_array($arg))
        {
            validate_scalar($arg);
        }
        else
        {
            if (!is_scalar($arg))
            {
                  // throwing an exception here if not scalar.
            }
        }
    }
    return true;
}

Is there any method to achieve this functionality? Please help me on this.

9
  • 1
    Either there is a static missing in the function declaration, or the self in self::validate_scalar is wrong. Commented Jun 13, 2014 at 12:21
  • Thanks. I have just modified the sample code. Commented Jun 13, 2014 at 12:23
  • array_walk_recursive Goes through every item recursively that is not an array and executes the callback/function on them. Commented Jun 13, 2014 at 12:28
  • hmm could you explain what you mean by "not going through all the elements of the array"? I tested the code as is and it catches everything PHP does not consider to be a scalar (array, resource, object). codepad.org/g9QR2eqJ Commented Jun 13, 2014 at 12:48
  • What's the question? Your original code works when I add a throw where the comment is. Commented Jun 13, 2014 at 12:48

1 Answer 1

1

array_walk_recursive

You could use something like this:

<?php

$array = array(
    'kalle' => 'asdf', 
    'anka' => array(
        123, 
        54324, 
        new stdClass()
    )
);

array_walk_recursive($array, function ($item, $key) {
    if (!is_scalar($item)) {
        echo $key . " =>  : Is not scalar\n";
        return false;
    }
    echo $key . " =>  : Is scalar\n";
    return true;
});

array_walk_recursive ignores values that are arrays

output:

kalle =>  : Is scalar
0 =>  : Is scalar
1 =>  : Is scalar
2 =>  : Is not scalar
Sign up to request clarification or add additional context in comments.

Comments

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.