Aminul
Aminul

Reputation: 25

How to pass variable value in php array

From WordPress custom text field values come: Like

text_field_words = 'Orange','Mango','banana' 

With

$var_word= get_option('text_field_words');

Now I want to use this variable in Array. I tried but value assigned as single value. Please help.

$my_array = array($var_word); 

Upvotes: 0

Views: 521

Answers (3)

Rakesh Jakhar
Rakesh Jakhar

Reputation: 6388

text_field_words should be a string, i. e. 'Orange,Mango,banana' OR "'Orange','Mango','banana'"

$var_word = "'Orange','Mango','banana'";
$my_array = explode(',',str_replace("'", '', $var_word));

DEMO:- https://3v4l.org/0FM5p

Upvotes: 0

LF-DevJourney
LF-DevJourney

Reputation: 28529

You php script receive a string text_field_words, so you just need to do is explode it into array.

$my_array = explode(",",$var_word);

Upvotes: 0

HPTheWebNuts
HPTheWebNuts

Reputation: 81

Let's clear something first.

This line of yours

text_field_words = 'Orange','Mango','banana' 

Should be

$text_field_words = 'Orange, Mango, banana';

If you're storing this string into wp_option table you can get those values using

$text_field_words = get_option( 'your_option_key', '' );

Now to your question you can get string into array as follows: (You've $text_field_words and it has your string "Orange", ... )

$text_field_words_array = explode(",", $text_field_words);
print_r($text_field_words_array);

Output:

Array
(
    [0] => Orange
    [1] =>  Mango
    [2] =>  banana
)

Upvotes: 1

Related Questions