How would i find the length of an element within an array, to make sure each is over 2 characters long. Using php that is...
ex. $this_array=array ("this", "and", "this", "and", "th")
foreach($this_array as $val) {
$valLength = strlen($val); //gives length
if($valLength < 3) {
//something here, less than 2 char
}
}
foreach ($this_array as $key => $value)
{
if (strlen($value) < 3)
{
echo "{$value} is too short<br />";
}
}
See foreach
foreach($this_array as $value) {
$strlen = strlen($value);
if($strlen <= 2)
{
echo '$value is '.$strlen.' characters long<br />';
// do something with it
}
}
Looping may be a bit overkill, unless there's more you need to do - filtering is much more effective.
<?
$this_array = array("a", "this", "and", "this", "and", "th");
$this_array = array_filter($this_array, function($val){return strlen($val)>=2;});
print_r($this_array); // Array ( [1] => this [2] => and [3] => this [4] => and [5] => th )
Note: This will only work in PHP 5.3+
$this_array=array ("aa", "bb", "cc", "asd", "aa");
function lengthCheck($v, $w)
{
global $lengthOK;
$len= strlen($w);
if($len<3)
{
$lengthOK=false;
}
return $lengthOK;
}
$lengthOK=true;// set everytime when you call "lengthCheck"
$b = array_reduce($this_array, "lengthCheck");
var_dump($b);
$b will have true/flase. i.e. TRUE if all elements have length 3 or more, false otherwise.