James Doe Jr.
James Doe Jr.

Reputation: 27

PHP is_array returns "1" on true and breaks on false

I am passing a jQuery array to PHP. My call back function returns the value when it is a string, but breaks when sending an array. The break is in the PHP code.

I've tested the following:

$yes = array('this', 'is', 'an array');
echo is_array($yes);

Which returns "1".

$yes = "array";
echo is_array($yes); 

Which breaks the code.

Why am I not returning "true" and "false"?

Upvotes: 0

Views: 1698

Answers (4)

Glaubule
Glaubule

Reputation: 169

$test_array = ( (array)$var === $var )? true : false;
if( $test_array ) ...

or

function test_array( $var )
{
    return (array)$var === $var;
}
//...the anywhere else ...
if( test_array( $my_var) )...

if you want to display your data and its type, simply use :

var_dump( $my_var );

Upvotes: 0

$yes = array('this', 'is', 'an array');
echo is_array($yes); 

output -- >1

as is_array($yes) returns true equivalent to echo true; which outputs 1

$yes = "array";
echo is_array($yes);//missing semicolon 

output(nothing) -->

as is_array($yes) returns false equivalent to echo false; which outputs nothing

From the Manual

A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string values.

so it's better if you code

echo (is_array($yes)) ? 'do something condition is true' : 'do something condition is false';

Upvotes: 1

chris-l
chris-l

Reputation: 2841

Try something like this:

echo is_array($yes) ? 'true' : 'false';

If you are wondering why is that necessary, that is, why just doing echo is_array($yes) is not enough, check this example: http://codepad.org/PcCbvTGe

As you can see, true is output as 1 and false produces no output.


A test done using an if: http://codepad.org/OIOZLqFc

<?php
$yes = array("trtr");
if(is_array($yes)) {
   echo "is an array";
} else {
   echo "is not";
}

Upvotes: 1

Peter Foti
Peter Foti

Reputation: 5654

If the code you posted is straight from your text editor then the lack of a semicolon at the end of echo is_array($yes) is the reason its breaking.

Edit: Just to clarify you're returning true/false, just not in the form of 1 or 0. You should be using is_array() in conjunction with a conditional.

$yes = 'asdf';

if (is_array($yes)){
    echo 'true';
} else {
    echo 'false';
}

Returns false

$yes = array('this', 'is', 'an', 'array');

if (is_array($yes)){
    echo 'true';
} else {
    echo 'false';
}

Returns true

Upvotes: 1

Related Questions