Max Koretskyi
Max Koretskyi

Reputation: 105439

How to convert params to array

I receive the following URL

/articles?difficulty=1,2

Inside the framework I want to receive an array from that - [1,2]. Is there any method in the framework to convert params like that into an array automatically? Can the framework do that? I can do like that explode(',', $params['difficulty']) - but I'm wondering whether this can be handled by the framework.

I don't want to pass params like that:

/articles?difficulty[]=1&difficulty[]=2

Upvotes: 1

Views: 576

Answers (2)

arogachev
arogachev

Reputation: 33538

There is no helper in framework Request component for converting such values, it can be easily achieved with native PHP explode function. Use:

$array = explode(',', $string);

as you suggested.

But the wrapper of explode exists - \yii\helpers\StringHelper::explode(), it has additional options for trimming and skipping empty elements, you can use it too. But most of the times using regular explode should be enough.

Upvotes: 3

Amitesh Kumar
Amitesh Kumar

Reputation: 3079

try this

Use the Request class.

http://www.yiiframework.com/doc-2.0/yii-web-request.html

print_r(Yii::$app->request->get()); returns all get variables in an array. It's like doing print_r($_GET); in straight php.

If you want a specific $_GET variable you access it as follows:

Yii::$app->request->get('difficulty');

In your case it would be:

$success = Yii::$app->request->get('success');
$token = Yii::$app->request->get('token');

Then after that explode it with comma, so it will get converted into array.

$array = explode(',', $success );

Upvotes: 0

Related Questions