views:

107

answers:

1

How to convert a string format into an array format?

I have a string, $string = 'abcde'

I want to convert it to a 1 element array

$string[0] = 'abcde'

Is there a built in function for this task? Or the shortest way is to

$string = 'abcde';
$array[0] = $string;
$string = $array;

TIA

+1  A: 

All kinds of ways in php..

$array = array('abcde');

$array[] = 'abcde';

Etc... not too sure what you're going for.

Edit: Oh, I think you might want to convert the first variable? Like this?

//Define the string
$myString = 'abcde';

//Convert the same variable to an array
$myString = array($myString);

Edit 2: Ahh, your comment above I think clears it up a little. You're getting back either an array or a string and don't know which. If you do what I just said above, you might get an array inside an array and you don't want that. So cast instead:

$someReturnValue = "a string";
$someReturnValue = (array)$someReturnValue;
print_r($someReturnValue);

//returns
Array
(
    [0] => a string
)


$someReturnValue = array("a string inside an array");
$someReturnValue = (array)$someReturnValue;
print_r($someReturnValue);

//returns
Array
(
    [0] => a string inside an array
)
Entendu
Thanks, that saves me 2 lines of code
Jamex
You could use the (array) cast. Going to edit the answer to show you.
Entendu
Great, I will keep the second part of your answer in mind. The first part actually saved me a bunch of if condition codes.
Jamex