Remove multiple spaces from given string

Write a program to remove the multiple spaces from the given string

String str = “You     are     a                good   boy.”

Output: “You are a good boy”

  1. <?php
  2.  
  3. //without pattern mach
  4. $str = "I am a good boy";
  5. $str_length = strlen($str);
  6. $str_arr = str_split($str);
  7. for ($i = 0; $i < $str_length; $i++) {
  8. if (isset($str_arr[$i + 1])
  9. && $str_arr[$i] == ' '
  10. && $str_arr[$i] == $str_arr[$i + 1]) {
  11. unset($str_arr[$i]);
  12. } else {
  13. continue;
  14. }
  15. }
  16.  
  17. echo implode("", $str_arr);
  18. ?>

Total digits of integer value

Write a program to find the total digits of a integer value without converting them into string

int a = 3421111

output: 7

 

  1. <?php
  2.  
  3. function total_digit_of_integer($int_val) {
  4. $go_running = true;
  5. $no_of_digits = 0;
  6. $nines = 0;
  7. //make integer to positive
  8. if ($int_val < 0) {
  9. $int_val = -($int_val);
  10. }
  11. while ($go_running == TRUE) {
  12. $nines = (int) ($nines );
  13. if ($int_val > $nines || $int_val == 0) {
  14. $int_val = ($int_val == 0) ? 1 : $int_val;
  15. $no_of_digits++;
  16. $nines = $nines . '9';
  17. } else {
  18. $go_running = FALSE;
  19. }
  20. }
  21. return $no_of_digits;
  22. }
  23.  
  24. echo total_digit_of_integer(-10);
  25. ?>