-1

I have been creating arrays from plain text by using comma , (or any other special character) with the help of php's explode() function like

$rawPhoneNumber = "800-555-5555"; 
$phoneChunks = explode("-", $rawPhoneNumber);
echo "Raw Phone Number = $rawPhoneNumber <br />";
echo "First chunk = $phoneChunks[0]<br />";
echo "Second chunk = $phoneChunks[1]<br />";
echo "Third Chunk chunk = $phoneChunks[2]";

But How can I create an associative array? Like how can I create an array like

$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

from a plain text like "Peter=>35,Ben=>37,Joe=>43"

Alfred
  • 21,058
  • 61
  • 167
  • 249

6 Answers6

2

I am sure there are more elegant ways, but... this should work, too.

$str='Peter=>35,Ben=>37,Joe=>43';
$arr=explode(',',$str);
$final=array();
foreach ($arr as $value) {
$val=explode('=>',$value);  
$final[$val[0]]=$val[1];    

}

print_r($final);
sinisake
  • 11,240
  • 2
  • 19
  • 27
1

Hell, why not. A two-line PHP 5.5+ solution using array_column and friends:

$input  = 'Peter=>35,Joe=>37';

$chunks = array_chunk(preg_split('/(=>|,)/', $input), 2);
$result = array_combine(array_column($chunks, 0), array_column($chunks, 1));

print_r($result);

Array
(
    [Peter] => 35
    [Joe] => 37
)
bishop
  • 37,830
  • 11
  • 104
  • 139
0
    <?php

$rawPhoneNumber = "800-555-5555"; 
$phoneChunks = explode("-", $rawPhoneNumber);

$myarray['Raw Phone Number'] = $rawPhoneNumber;
$myarray['First chunk'] = $phoneChunks[0];
$myarray['Second chunk'] = $phoneChunks[0];
$myarray['Second chunk'] = $phoneChunks[0];
$myarray['Third chunk'] = $phoneChunks[0];

Result:
echo "<pre>";
print_r($myarray);
echo "</pre>";

?>

------------- Think this will work for you -----------------

<?php

$sample = "Peter=>35,Ben=>37,Joe=>43"; $row_chunks = explode(",", $sample);

foreach ($row_chunks as $value) 
{
    $row_chunks = explode("=>", $value);
    $myarray[$row_chunks[0]]=$row_chunks[1];
}

echo "<pre>";
print_r($myarray);
echo "</pre>";
?>
MenukZ
  • 79
  • 6
  • whats wrong with my answer ? please explain – MenukZ Sep 24 '15 at 16:46
  • Yours is a manual solution, not automatic. The array may have fewer or larger number of entries. The key name varies. Got it? – Alfred Sep 24 '15 at 16:56
  • Fine but you didn't mention it in the question. could you please provide a sample output that you need ? your question is not clear – MenukZ Sep 24 '15 at 17:01
0

Looking your condition this will work

<?php
$content = 'Peter=>35,Ben=>37,Joe=>43';
$arr = explode(',',implode(',',explode('=>',$content)));
$assoArray = Array();
for($i =0; $i < sizeof($arr); $i +=2)
{
    $assoArray[$arr[$i]] = $arr[$i +1];
}
print_r($assoArray);
?>
Samundra Khatri
  • 997
  • 1
  • 9
  • 18
0

You can use eval, array_walk, foreach with an explode, or even strtok:

$input = 'Peter=>35,Ben=>37,Joe=>43';
$array = array ();

$part = strtok($input, ',');
while (false !== $part) {
    list ($name, $age) = explode('=>', $part);
    $array[$name] = $age;
    $part = strtok(',');
}

print_r($array);

There is virtually no end to the convoluted ways you can do this.

Community
  • 1
  • 1
bishop
  • 37,830
  • 11
  • 104
  • 139
-1

Your input format is close enough to PHP native to suggest eval:

$ages = eval('return array(' . file_get_contents('ages.txt') . ');');
print_r($ages);

Example:

$ cat ages.txt
Peter=>35,Ben=>37,Joe=>43
$ php example.php
Array
(
    [Peter] => 35
    [Ben] => 37
    [Joe] => 43
)

But for security and performance reasons, you're better off using string manipulation.


If you want to keep data in file, using PHP data structures, I'd suggest using var_export and writing to a file you later include:

$ages = array ('Peter' => 35, 'Ben' => 37 );
file_put_contents('ages.php', '<?php return ' . var_export($ages, true) . ';');

$readback = include('ages.php');
print_r($readback);

Example:

$ php example.php
Array
(
    [Peter] => 35
    [Ben] => 37
)
$ cat ages.php
<?php return array (
  'Peter' => 35,
  'Ben' => 37,
);
miken32
  • 42,008
  • 16
  • 111
  • 154
bishop
  • 37,830
  • 11
  • 104
  • 139
  • 1
    But sanitise the hell out of your input before doing this! – Siguza Sep 24 '15 at 16:36
  • you say that the other code has more performance than my current input text and our code? – Alfred Sep 24 '15 at 16:43
  • @blasteralfredΨ Just saying that, in general, `eval` and `file_get_contents` are not going to be super efficient. If you want to store the data in a file, in a PHP like syntax, then you're better off doing something like my edit. – bishop Sep 24 '15 at 16:50
  • Any way, I am not using a file and the text is retrieved from mysql db. So what do you suggest? My "php like" text solution or the other solution from the linked qn? – Alfred Sep 24 '15 at 16:54
  • @blasteralfredΨ You're not using a file? But your OP said *<35,Ben=>37,Joe=>43">>*... Anyway, if this string is stored in a DB, I'd suggest using a proper ages table. If not that, then I'd suggest string manipulation. I've added another answer using `strtok`, which might be more to your liking. – bishop Sep 24 '15 at 17:04
  • @blasteralfredΨ http://stackoverflow.com/q/951373/2908724 – bishop Sep 24 '15 at 17:51
  • This will solve my problem for now. I will be *very very careful* – Alfred Sep 25 '15 at 02:55