Ivan Topić Ivan Topić - 3 days ago 5
PHP Question

Using arrays which has empty items in array that are not set as null or false

Is it possible for this array type to work? I have many fields and I would prefer if I could skip placing

false
or
null
instead of empty field. I got this list from CSV file and I only need to use this array once. Currently I get

Parse error: syntax error, unexpected ',', expecting ')


If it is not possible any suggestion on how to replace empty fields to null are welcome :)

$array = array(
array('apples','bananas','figs',,,'apples2'),
array('lemon',,'bananas3','figs2','apples3',,'apples3'),
array('apples',,,'bananas','figs',,,,'apples2'),
...
);


foreach($array as $post) {
// something once
}

Answer

Try that it should solve the problem (it may give you NOTICE error but don't pay attention):

$str = "array(
array('apples','bananas','figs',,,'apples2'),
array('lemon',,'bananas3','figs2','apples3',,'apples3'),
array('apples',,,'bananas','figs',,,,'apples2')
);";

function convert_to_right_array($str) {
    $points = [];
    for ($i = 0; $i < strlen($str); $i++) {
        if ($str[$i] == ',' && $str[$i+1] == ',') {
            $point = [$i, $i + 1];
            $points[] = $point;
        }
    }
    $newStr = '';
    $startChar = 0;
    foreach ($points as $point) {
        $part = substr($str, $startChar, $point[0] - $startChar);
        $part = ($part[strlen($part) - 1] == ',' ? $part : $part . ',' );
        $newStr .= $part;
        $newStr .= 'null';
        $startChar = $point[1];
    }
    $newStr .= substr($str, $startChar, strlen($str));
    return $newStr;
}
Comments