user2534252
user2534252

Reputation: 105

PHP Convert variable to array

My variable like this,

$a = "A1|A2|A3|";

so how to convert php array?

to this,

$a=array("A1","A2","A3");

Upvotes: 0

Views: 96

Answers (6)

arunrc
arunrc

Reputation: 628

$a=explode('|',$a);

Check this link

explode

explode — Split a string by string

Description: array explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] )

Upvotes: 0

Pankaj katiyar
Pankaj katiyar

Reputation: 464

$a = "A1|A2|A3|";
print_r(array_filter(explode("|", $a)));

Upvotes: 0

Basit
Basit

Reputation: 1840

You can do achieve what you want to this way:

$a = "A1|A2|A3|"; 
$a = rtrim($a, '|'); // Trimming the final |
$exploded = explode("|", $a); // Extracting the values from string.
var_dump($exploded);

Hope it answers your question. Refer rtrim and explode on official documentation site for more relevant details.

Upvotes: 1

v2solutions.com
v2solutions.com

Reputation: 1439

Use explode function.

$a = rtrim("|", $a);
$a = explode('|', $a);
print_r($a);

Upvotes: 3

Punitha Subramani
Punitha Subramani

Reputation: 1477

$a = "A1|A2|A3|";
$newA = explode("|",$a);
print_r($newA);

Upvotes: 0

alex
alex

Reputation: 490153

First, trim off the pipe at the end of your input.

$str = rtrim($a, '|');

Then, explode on the pipe.

$a = explode('|', $str);

Alternatively, do the split normally and then filter out the whitespace entries as a post-processing step.

$a = array_filter($a, 'strlen');

Upvotes: 4

Related Questions