Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pick a value in php array

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; 

?>







    

   

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading