SliQz
SliQz

Reputation: 282

deleting specific value of array

I have an array containing the numbers 1 to 10. When i select one random array key, i want to delete this one The following code does something like it, but just not good enough.

$imgArray = range(1,9);
$rand_key = array_rand($imgArray);
$imgValue = $imgArray[$rand_key];
unset($imgArray[$imgValue]);

The code deletes a value from the array, but it deletes the wrong one, Echoing the array gives the following result:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
)

Random selected item would be like number 4 but then it deletes array KEY 4, not array value 4..

Is there any way to change that? besides changing the variable(using -1)?

Upvotes: 1

Views: 126

Answers (4)

Nono
Nono

Reputation: 7302

Try this:

// Create array
$imgArray = range(1,9);

// Get random key from array
$rand_key = array_rand($imgArray);

// Get key value from array
$imgValue = $imgArray[$rand_key];

// Delete value from array
unset($imgArray[array_search($imgValue,$imgArray)]);


Here is your array:
Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
)

rand_key: 2

imgValue: 3

After delete imgValue: 3

New Array
(
    [0] => 1
    [1] => 2
    [3] => 4
    [4] => 5
    [5] => 6
    [6] => 7
    [7] => 8
    [8] => 9
)

Upvotes: 0

ChristopheBrun
ChristopheBrun

Reputation: 1207

You are confusing keys and values, that's why. $imgArray is a range(1,9) but that's values. Your keys are range(0,8).

So *$rand_key* is actually not a random key but a random value.

Thus you delete the wrong... key and you're exposes to an OutOfBounds exception.

If you want to randomize searched values, the use array_search to retrieve and process the key

If you want to randomize searched keys, then use range(0,8).

Upvotes: 0

Vineet1982
Vineet1982

Reputation: 7918

As such there is no way to delete the unset the value by function but the You pay the trick for simplest function? Well, you won't find anything simpler.

$array=array(312, 401, 1599, 3);
$toDelete=401;

$array=array_diff($array, array($toDelete));

Upvotes: 7

Jon
Jon

Reputation: 437554

array_search will return the key for the value that you search for, if it finds it:

$rand_key = array_rand($imgArray);
$imgKey   = array_search($imgArray[$rand_key]);

if ($imgKey !== false) {
    unset($imgArray[$imgKey]);
}

Of course you don't really need to do this, because $rand_key is already a key in the array (array_rand returns a key!) so the code reduces to:

$rand_key = array_rand($imgArray);
// optional, if you need the value for something:
// $rand_val = $imgArray[$rand_key];
unset($imgArray[$rand_key]);

Upvotes: 5

Related Questions