Reputation: 6900
How can I limit the character length of all string inside an array?
Like chunk_split ( $string, 10 );
$array = array(
"foo" => "bar",
"bar" => "foofoofoofoofoofoofoo",
"name" => "name34234242224"
);
I do not want more than 10 characters in any string.
Upvotes: 0
Views: 104
Reputation: 3870
Like this:
foreach($array as $key => $value){
$array[$key] = substr($value,0,10);
}
Upvotes: 1
Reputation: 467
you can loop each element with a foreach and get first 10 characters. this function is static. it means it won't check for new element anymore. you could create a check method for each new element inserted.
foreach ($array as $key => value) {
$array[$key] = chunk_split($value, 10);
}
now, for every element you will insert, call this function for check the length of the string:
function newElement($array, $element) {
array_push($array, substring($element, 10));
return $array;
}
Upvotes: 0
Reputation: 6206
$array = array_map(function($value) {
return substr($value, 0, 10);
}, $array);
Upvotes: 2
Reputation: 44714
Loop through each item in the array, and run chunk_split()
on it:
foreach ($array as $key => value) {
$array[$key] = chunk_split($value, 10);
}
Upvotes: 0