Reputation: 91
I'm trying to set the max length of each post on a site, but strlen() doesn't work with arrays. So I need to break it down to check each post in the array.
How could I adapt what I have to get this if statment to work correctly. The issue is the strlen() not accepting object.
for($i = 0, $size = count($somePosts); $i < $size; ++$i) {
if (strlen(utf8_decode($somePosts[$i])) > $max_length) {
$offset = ($max_length - 3) - strlen($somePosts);
$somePosts = substr($somePosts, 0, strrpos($reviewPosts, ' ', $offset)) . '...';
}
}
I'm using Doctrine to generate the array, which works fine.
Thanks.
Edit:
Error - Warning: strlen() expects parameter 1 to be string, object given
Edit 2:
No error messages now, but the code doesn't work in terms of limiting the length of the posts.
Upvotes: 0
Views: 4093
Reputation: 15650
As alternative you can use array_map
<?php
$strs = array('abcdefgh', 'defghjklmn', 'ghjefggezgzgezg');
$max = 5;
$strs = array_map(function($val) use ($max) {
if (strlen($val.'') < $max) return $val.'';
return substr($val.'', 0,$max-3).'...';
},$strs);
var_dump($strs);
EDIT implicit casts added to cast object to string
Upvotes: 0
Reputation: 3160
You need to access the current array item like $somePosts[$i]
and not $somePosts
for($i = 0, $size = count($somePosts); $i < $size; ++$i) {
if (strlen(utf8_decode($somePosts[$i])) > $max_length) {
$offset = ($max_length - 3) - strlen($somePosts[$i]);
$somePosts[$i] = substr($somePosts[$i], 0, strrpos($reviewPosts, ' ', $offset)) . '...';
}
}
Upvotes: 3