0

I made this code in order to pick up a value a from an array, delete it, show the array without the deleted element and show which element has been deleted. If i run the code, the index number goes but the char stays.

Can you help me to understand where i'm wrong? What i would reach is just to have only the charset and then the charset with the missing value, but not the indexes.

    <?php
// i create the array 
$charset = range(",","|");
    echo "Original Array <br>";

// I show the original array
print_r($charset);


// i put in a variable a random number from the set given
$random= array_rand($charset,1);
// using the unset function, i delete the chosen number previously stored in the variable
unset($charset[$random]);

echo "After delete the element <br>";

// Display Results
print_r($charset);
//here show the number that has been deleted

echo "<br>";
echo "The deleted char is " .$random; 

?>







    

   
2

1 Answer 1

0

array_rand() gets a random index not value. So the $random variable holds a random array index. So you are deleting a random character by that character's index in the array, but you never store what character that is anywhere. try storing the character in a new variable before deleting the character from the array, like this.

// i put in a variable a random number from the set given
$random= array_rand($charset,1);
// store the character i am about to delete
$deleted_character = $charset[$random];
// using the unset function, i delete the chosen number previously stored in the variable
unset($charset[$random]);

echo "After delete the element <br>";

// Display Results
print_r($charset);
//here show the number that has been deleted

echo "<br>";
echo "The deleted char is " . $deleted_character . ". It's index in the array was " . $random;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.