2

I want to get the value of an array type given a certain index. The array's values are

$status = [1,2];

And I used these code to get the value:

$task_state = $status[1];

But it actually thought $status is a string and returns

'['

I know that this is actually quite simple, but I just can't seem to find the answer to my problem. Thank you

3
  • Your array gives an actual result. but if you face problem then try with declare $status as array $status = array(); like this. Commented Jun 7, 2017 at 3:43
  • What PHP version are you using? Using [] to define arrays is only supported in PHP >= 5.4 Commented Jun 7, 2017 at 3:52
  • it is 7.0.10 sir Commented Jun 7, 2017 at 3:54

3 Answers 3

2

If $status defined as a string, you can return php value of it with eval function like below:

$status = '[1,2]';
$status_array = eval('return ' . $status . ';');
$task_state = $status_array[0];

Caution The eval() language construct is very dangerous because it allows execution of arbitrary PHP code. Its use thus is discouraged. If you have carefully verified that there is no other option than to use this construct, pay special attention not to pass any user provided data into it without properly validating it beforehand.

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

Comments

0

i try to copy your script and here what i get

$status = [1,2];
$task_state = $status[1];
var_dump($status);
exit;

the result is :

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

can you give me line of your code for displaying '['. may be your php version is the problem. See refrence.

2 Comments

is it when i echo $task_state sir
try to use array(1, 2) instead [1, 2]
0

Maybe you are saying that the values of your array:

$status  = array(1,2);

So to get a value from the array:

echo $tatus[0] . "and " . $tatus[1];

output:

1 and 2

1 Comment

actually i was trying to get post values from my android apps using $status = $_POST['state']; But I am already sure the value is [1,2], since I actually have tried to put and test it manually using postman

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.