Jump to content

Even length strings?


Guardian-Mage

Recommended Posts

I have an array with a few values. This array is called $array. I want to find the biggest string in the array, and make all of the other strings in the array the same length by adding whitespace. How should I go about doing this, and I know how to add whitespace, just not how to find the biggest string and do everything else. For example:

 

$array[0] = "asmllstr";                #8 Characters
$array[1] = "amediumstri";          #11 Characters
$array[2] = "abiggerstring";         #13 Characters
$array[3] = "thisisclearlybiggest"; #20 Characters
$array[4] = "smaller";                 #7 Characters

#This would become
$array[0] = "asmllstr            ";    #20 Characters
$array[1] = "amediumstri         ";  #20 Characters
$array[2] = "abiggerstring       ";  #20 Characters
$array[3] = "thisisclearlybiggest"; #20 Characters
$array[4] = "smaller             ";    #20 Characters

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/91359-even-length-strings/
Share on other sites

try

<?php
$array[0] = "asmllstr";                #8 Characters
$array[1] = "amediumstri";          #11 Characters
$array[2] = "abiggerstring";         #13 Characters
$array[3] = "thisisclearlybiggest"; #20 Characters
$array[4] = "smaller";                 #7 Characters
$max_len = -1;
foreach ($array as $s){
$x = strlen($s);
if ($x > $max_len){
	$max_len = $x;
}
}
foreach ($array as $k => $v) $array[$k] = str_pad($v, $max_len);
?>

Link to comment
https://forums.phpfreaks.com/topic/91359-even-length-strings/#findComment-468139
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.