0

My variable like this,

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

so how to convert php array?

to this,

$a=array("A1","A2","A3");
1
  • 7
    $a = explode('|', $a); It's one of the functions most people learn before anything else Commented Aug 21, 2014 at 7:13

6 Answers 6

4

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');
Sign up to request clarification or add additional context in comments.

1 Comment

+1 Only correct answer on this question. Without trimming last pipe, you will get empty element in array. I don't understand how other answers has got upvote.
3

Use explode function.

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

1 Comment

check @alex answer. You need to trim the last | or else you will get last empty element in array.
1

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.

1 Comment

+1 for trimming the last pipe and mentioning comments as well in answer.
0
$a = "A1|A2|A3|";
$newA = explode("|",$a);
print_r($newA);

1 Comment

check @alex answer. You need to trim the last | or else you will get last empty element in array.
0
$a = "A1|A2|A3|";
print_r(array_filter(explode("|", $a)));

Comments

0
$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 ] )

1 Comment

check @alex answer. You need to trim the last | or else you will get last empty element in array.

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.