CSI: PHP

"Looking at your tweets I cannot even fathom what your job is. CSI:PHP?" — @grmpyprogrammer

Stop Rolling Your Own

| Comments

Seriously. Stop it. Or you’ll end up with garbage like this, in which a developer writes two separate functions for converting JSON to an array, only one of which is compatible with json_decode. Yes, both are in production.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php

function jsonToArray($jsonData)
{

    $newArray = array();

    // remove first and last []
    $length = strlen($jsonData) - 2;
    $jsonString = substr($jsonData, 1, $length);

    if ($jsonString != "") {
        // tokenize, using , as a divider
        $newArray = explode(",", $jsonString);
    }
    return $newArray;
}

// Converts JSON data string to PHP array
// Assumes this format: ["Some text","Even more text"]
function jsonStringsToArray($jsonData)
{

    // remove first and last []
    $length = strlen($jsonData) - 2;
    $jsonString = substr($jsonData, 1, $length);

    // tokenize, using , as a divider
    $newArray = explode(",", $jsonString);

    $lastArray = array();

    for ($i = 0; $i < sizeof($newArray); $i++) {

        $thisLength = strlen($newArray[$i]) - 2;
        $lastArray[] = substr($newArray[$i], 1, $thisLength);
    }
    return $lastArray;
}

Comments