Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php: String indexing inconsistant?

Tags:

arrays

php

I have created a function which randomly generates a phrase from a hardcoded list of words. I have a function get_words() which has a string of hardcoded words, which it turns into an array then shuffles and returns.

get_words() is called by generate_random_phrase(), which iterates through get_words() n times, and on every iteration concatenates the n word into the final phrase which is destined to be returned to the user.

My problem is, for some reason PHP keeps giving me inconsistent results. It does give me words which are randomized, but it gives inconsistent number of words. I specify 4 words as the default and it gives me phrases ranging from 1-4 words instead of 4. This program is so simple it is almost unbelievable I can't pinpoint the exact issue. It seems like the broken link in the chain is the $words array which is being indexed, it seems like for some reason sometimes the indexing fails. I am unfamiliar with PHP, can someone explain this to me?

<?php

function generate_random_phrase() {
  $words = get_words();
  $number_of_words = get_word_count();
  $phrase = "";
  $symbols = "!@#$%^&*()";
  echo print_r($phrase);

  for ($i = 0;$i < $number_of_words;$i++) {
  $phrase .= " ".$words[$i];
}


  if (isset($_POST['include_numbers']))
    $phrase = $phrase.rand(0, 9);

  if (isset($_POST['include_symbols']))
    $phrase = $phrase.$symbols[rand(0, 9)];

  return $phrase;
}

function get_word_count() {
  if ($_POST['word_count'] < 1 || $_POST['word_count'] > 9) 
    $word_count = 4; #default
  else
    $word_count = $_POST['word_count'];
  return $word_count;
}

function get_words() {
  $BASE_WORDS = "my sentence really hope you 
    like narwhales bacon at midnight but only 
    ferver where can paper laptops spoon door knobs 
    head phones watches barbeque not say";
  $words = explode(' ', $BASE_WORDS);
  shuffle($words);
  return $words;
}
?>
like image 681
chopper draw lion4 Avatar asked Mar 09 '26 11:03

chopper draw lion4


1 Answers

In $BASE_WORDS your tabs and new lines are occupying a space in the exploded array that's why. Remove the newlines and tabs and it'll generate the correct answer. Ie:

$BASE_WORDS = "my sentence really hope you like narwhales bacon at midnight but only ferver where can paper laptops spoon door knobs head phones watches barbeque not say";
like image 161
zephinzer Avatar answered Mar 12 '26 00:03

zephinzer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!