2

So I have this array:

$myArray = array('myVar', 'myVar75', 'myVar666');

How do I isset check whether the variable called $myVar,$myVar75,$myVar666 exists or not?

What is the most sensible way of passing the array's value into the isset() function as a variable name to check?

3 Answers 3

1

Just use variable variables to test each element with a simple foreach loop:

Example:

$myVar666 = 1; // for example's sake
$myArray = array('myVar', 'myVar75', 'myVar666');
foreach($myArray as $element) {
    if(isset(${$element})) {
        echo $element, ' is already set';
    } else {
        echo $element, ' is not yet set';
        // if not set, do something here
    }
}

Should yield something like this:

$myVar is not yet set 
$myVar75 is not yet set 
$myVar666 is already set 
Sign up to request clarification or add additional context in comments.

2 Comments

i think he want to create variable first with the values of array and then want to use isset on thiose variables
@Anant $myVar666 above is just an example, just to demonstrate the output, the OP could just do anything within the if block whatever the OP decides to do
1
foreach($myArray as $value){
    if(isset($$value)){
        echo "$value is exist with value : '".$$value."'";
    }
    else{
        "$value is not exist";
    }
}

Comments

1

You'd do that by putting an extra $, as follows:

$myArray = array("myVar", "myVar75", "myVar666");

if (isset($$myArray[0])) {
    //Content
}

That would check if $myVar is set. Change the index to myArray accordingly.

The way to think about PHP's implementation of this (called variable variables) is that the content of the string goes after the dollar sign:

$hi = "hello";

But if you put $$hi, then the $hi is replaced with the string's content, so it becomes $hello.

$hi = "hello";

$hello = "greetings";

If you put $$$hi, then the $hi is replaced so that it becomes $$hello, and the $hello is replaced so that it becomes $greetings.

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.