0

I am trying to pull a variable out of an array with name of variable coming from another variable.

I have tried both: $get_results[$name] and $get_results->$name with no success.

I keep on getting following error on $get_results[$name]: Fatal error: Uncaught Error: Cannot use object of type stdClass as array in But on $get_results->$name it skips over it.

The $name is loaded by user. The $get_results is loaded by MYSQL database

$name = 'test2'
$get_results = array('test' - > '1', 'test2' - > '2');

if (!isset($get_results[$name])) {
  if (empty($get_results[$name])) {
    $value = $get_results[$name];
  } else {
    $value = "";
  }
}
elseif(!isset($_POST[$name])) {
  $value = Input::get($name);
} else {
  $value = "";
}

I am trying to get the value from $get_results from test2.


I have made the changes to my script:

    if(isset($get_results[$name])){
        if(!empty($get_results[$name])){
            $value = $get_results[$name];
        } else {
            $value = "";
        }
    }elseif(!isset($_POST[$name])){
        $value = Input::get($name);
    }else {
        $value = "";
    }

When I try to pull the data from $get_results[$name] its dies with error: Cannot use object of type stdClass as array

This shows the <code>$get_results</code> and <code>$name</code> loaded with variables. Error 1 Error 2

3 Answers 3

3

You are running into a syntax error while initializing your array. Associative array uses => rather than ->.

So, just replace

$get_results = array ('test' -> '1', 'test2' -> '2');

with

$get_results = array ('test' => '1', 'test2' => '2');
Sign up to request clarification or add additional context in comments.

Comments

1

your get_results variable returns an object

use this:

get_results->$name;

1 Comment

It fixed the issue. Thank You
1

First thing you have a syntax error in array creation update -> to =>.

do

$name = 'test2';
$get_results = array ('test' => '1', 'test2' => '2');
echo 'value will be : '.$get_results[$name];die;

Output:

value will be : 2

Second you have logic error too in if Please check below corrected code

$name = 'test2';
$get_results = array('test' => '1', 'test2' => '2');
if (isset($get_results[$name])) {//check if $name is in array will true
    if (!empty($get_results[$name])) {//check if $name in array is not empty
        $value = $get_results[$name];
    } else {
        $value = "test 1";
    }
} elseif (!isset($_POST[$name])) {
    $value = "test 2";//Input::get($name);
} else {
    $value = "test 3";
}
echo 'value will be : '.$value;die;

Output:

value will be : 2

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.