Reputation: 3859
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
);
Upvotes: 1
Views: 2684
Reputation: 685
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);
Upvotes: 2
Reputation: 3520
Since you want to send the array as part of an http request, you can prepare it with http_build_query
and count the strlen
of the chain returned by http_build_query
:
<?php
$data_array = array(
"end"=>array("dateTime"=>'end'),
"start"=>array("dateTime"=>'start'),
"summary"=>'name'
);
$http_build_query = http_build_query($data_array);
echo strlen($http_build_query);
Upvotes: 0