Question

Since I updated to php 5.4 i get the error Call-time pass-by-reference has been removed, as i read, removing the & should solve it. It does, but now my code does not work anymore.

I need to make an Associative Array out of the string raw400, with the keys beeing t and f plus the number (example t410 and f410) and the value must be the value after the - without the -

Example:

t410-1:06,f410-15.4

schould become:

key: t410
value: 1:06

key: f410
value 15.4

The code..

$raw400 = 't410-1:06,f410-15.4,t390-1:06,f390-15.6,t370-1:05,f370-16.0,t350-1:05,f350-16.2,t330-1:04,f330-16.3,t310-1:00,f310-16.7';

$array = explode(',',$raw400);
$nm400 = array();
array_walk($array,'walk', $nm400);
function walk($val, $key, $nm400){
$nums = explode('-',$val);
$nm400[$nums[0]] = $nums[1];
}

Help is greatly appreciated, thanks.

Was it helpful?

Solution

Simply make use of parse_str() for this trick.

<?php
$raw400 = 't410-1:06,f410-15.4,t390-1:06,f390-15.6,t370-1:05,f370-16.0,t350-1:05,f350-16.2,t330-1:04,f330-16.3,t310-1:00,f310-16.7';
parse_str(str_replace(array('-',','),array('=','&'),$raw400),$arr);
print_r($arr);

OUTPUT :

Array
(
    [t410] => 1:06
    [f410] => 15.4
    [t390] => 1:06
    [f390] => 15.6
    [t370] => 1:05
    [f370] => 16.0
    [t350] => 1:05
    [f350] => 16.2
    [t330] => 1:04
    [f330] => 16.3
    [t310] => 1:00
    [f310] => 16.7
)

Demo

OTHER TIPS

Use preg_match_all() and array_combine

<?php
$raw400 = 't410-1:06,f410-15.4,t390-1:06,f390-15.6,t370-1:05,f370-16.0,t350-1:05,f350-16.2,t330-1:04,f330-16.3,t310-1:00,f310-16.7';
preg_match_all("/([^-, ]+)\,([^-,]+)/", $raw400, $res);
$array = array_combine($res[2], $res[1]);
print_r($array);

OUTPUT:

 Array
(
    [f410] => 1:06
    [t390] => 15.4
    [f390] => 1:06
    [t370] => 15.6
    [f370] => 1:05
    [t350] => 16.0
    [f350] => 1:05
    [t330] => 16.2
    [f330] => 1:04
    [t310] => 16.3
    [f310] => 1:00
)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top