3

I was wondering if i could assign values to a variable inside an IF statement. My code is as follows:

<?php
    if ((count($newArray) = array("hello", "world")) == 0) {
        // do something
    }
?>

So basically i want assign the array to the $newArray variable, then count newArray and check to see if it is an empty array.

I know i can do this on several lines but just wondered if i could do it on one line

3 Answers 3

3

Try this:

if(count($newArray = array("Hello", "world")) == 0) {
    ....
}

I'd advice against this though, as it makes your code less readable. And highly illogical too as you know that the array in question contains two values. But perhaps you have something else in mind. :)

Sign up to request clarification or add additional context in comments.

Comments

2

Yeah, you can, like so:

if(count($ary = array(1,2,3)))

Doing a var_dump of $ary gives:

array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}

Comments

1

Actually you don't need to use count inside the if statement, because an empty array is considered to be false in PHP. See PHP documentation.

So your code can look like this:

if (!$newArray = array("hello", "world")) {
    echo "newArray is empty";
}

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.