0

Hi I have a simple question regarding the array.

I am trying to use foreach loop to echo the vars. However, there are times that the variable wont' be an array I have created a if statement to check the variable type, but I am not sure if it's the best practice doing it.

Are there any better way to do what I need? Thanks a lot!

My codes

$test = $_GET['testVar'];

if(is_array($test)){
 foreach($test as $t){
   echo $t;
 }
}else{
   echo $test;
}
1
  • 2
    Nope. That's how you would do it. Commented Mar 6, 2013 at 23:14

1 Answer 1

2

is_array is the best way to check if a variable is an array. So your code is ok.


However here comes a generic solution that will work for all data types not just arrays with the functiongettype() You can refine the results if $type is 'Object' using the function get_class()

$type = gettype($var);

// get class name for objects if so desired
if($type === 'object') {
    $type = get_class($var);
}
Sign up to request clarification or add additional context in comments.

5 Comments

I think OP is only concerned if it's an array; in which case is_array is perfectly suitable.
Ok maybe I misunderstood someting, however this is generic solution and should help in any case
Just stick to gettype and add that is_array is acceptable as well.
get_class doesn't work indeed. This is not JavaScript where everything is an Object-type :P. If you check for any type; use gettype() for unity. If you only check if it's an array, then use is_array as it returns a clean TRUE/FALSE :)
@AarolamaBluenk Thanks. Anwers to the easiest questions are most vulnerable for earning downvotes if not read 100% exactly ;) So I hope all are happy now :)

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.