Julian Schmuckli Julian Schmuckli - 9 months ago 62
HTTP Question

Get number of characters in an array?

I want to send a content length with a http request. For a normal string, I can use the function strlen(). But how do I using that for an array specially for a multidimensional array in PHP? I've found the following script to extract an array like the var_dump(). But what do I need for the Content-Length?

function count_array_chars($array){
foreach($array as $key => $value){
if (!is_array($value))
{
echo $key ." => ". $value ."\r\n" ;
}
else
{
echo $key ." => array( \r\n";

foreach ($value as $key2 => $value2)
{
echo "\t". $key2 ." => ". $value2 ."\r\n";
}

echo ")";
}
}
}


UPDATE:

$data_array = array(
"end"=>array("dateTime"=>$end),
"start"=>array("dateTime"=>$start),
"summary"=>$name
);

Answer Source

Assuming that you only want to count the values, you can use this approach:

$array = array(
    "1" => "abcd",
    "2" => "xyz"
);

function count_array_chars(array $array)
{
    $charNumber = 0;
    array_walk_recursive($array, function($val) use (&$charNumber)
    {
        $charNumber += strlen($val);
    });
    return $charNumber;
}

print count_array_chars($array);

If you also want to count the keys, it looks like that:

$array = array(
    "end" => array("dateTime"=>"end"),
    "start" => array("dateTime"=>"start"),
    "summary" => "name"
);

function count_array_chars(array $array)
{
    $charNumber = 0;
    array_walk_recursive($array, function($val, $key) use (&$charNumber)
    {
        $charNumber += strlen($val) + strlen($key);
    });
    return $charNumber;
}

print count_array_chars($array);