Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

declare or convert a string to array format PHP

Tags:

arrays

string

php

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

like image 772
Jamex Avatar asked Jun 07 '26 06:06

Jamex


1 Answers

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
)
like image 67
Entendu Avatar answered Jun 09 '26 00:06

Entendu