I am having a weird problem in PHP. I have an array with some integer values in it. When I try to compare the values in the array to a target integer, the index does not work with the array and also cannot be incremented. Here is an example.
The problem lies in the if($j == $indexOfExposed[$k])
/* This is a simple function to show some letters of a patient name, while the rest of letters are replaced with asterisks.
@Param: Patient name
@Return: limited preview of patient name;
*/
function encodeName($name){
$len = strlen($name); // This is the lenghth of $name. used to itterate and set a range.
$numOfExposedLetters = rand(1, 4); // Random value assigned to see how many letters of the name will be exposed.
$indexOfExposed = array(); // This is an array of indexes for exposed letters.
$k = 0; // This counter is used to traverse the $indexOfExposed array.
$encodedName = ""; // This is the value we will return after it is generated.
$previous = 0; // Used to keep track of previous value in the $indexOfExposed array. This is incase we have repeated values in the array;
/* This loop is used to append random values to the arary of indexes,
With $numOfExposedLetters being the quantity of exposed letters. */
for($i = 0; $i < $numOfExposedLetters; $i++){
$indexOfExposed[$i] = rand(2, $len);
}
sort($indexOfExposed); // Sort the array, for easier access.
/* Ecoding name */
for($j = 1; $j <= $len; $j++){
if($indexOfExposed[$k] == $previous){
$encodedName .= "*";
$k++;
continue;
}
if($j == $indexOfExposed[$k]){
$encodedName .= $name[$j-1];
$previous = $indexOfExposed[$k];
$k++;
}
else
$encodedName .= "*";
$k++;
} // end of encode
return $encodedName;
}
This code takes in a person's name and replaces the letters in the name with asterisks. random indexes with expose the actual letters in the name.
$indexOfExposed) in three lines of code:$encodedName = $name; foreach ($indexOfExposed as $idx) { $encodedName[$idx] = '*'; }. There is no need to sort$indexOfExposed(there is even no need to generate it, you can do the encoding on the fly). It doesn't expose but it masks the characters whose indices are generated in$indexOfExposedbut as long as the indices are randomly generated, it doesn't make any difference.