PhilD
PhilD

Reputation: 277

passing var as string to an array

Im sure this is super simple. im trying to pass values held in a var into another var as an array.

I have a var $guideinValue that contains string of values separated by commas. the values stand for category ids.

when i echo $guideinValue it shows 18,19 which are the proper category id's. im trying to use these in the wordpress var $selected_cats.

when i manually punch into $selected_cats = array(18,19); everything works and a print_r of 1$selected_cats1 shows Array ( [0] => 18 [1] => 19 )

but when i use $selected_cats = array($guideinValue);, a print_r shows Array ( [0] => 18,19 ) and nothing works ofc

Why does this happen and how do i fix my syntax?

Upvotes: 0

Views: 46

Answers (2)

VeeeneX
VeeeneX

Reputation: 1578

It's simple use explode function.

array explode ( string $delimiter , string $string [, int $limit ] );

Working example:

$array = explode(",", $guideinValue);

Upvotes: 1

Codew
Codew

Reputation: 494

This is the proper way with array_values(), array_filter() and explode()

$selected_cats = array_values(array_filter(explode(',', $guideinValue)));

explode() - Breaks string

array_filter() - Clears empty values

array_values() - Rearrange array indexes to start from 0

Upvotes: 1

Related Questions