0

Here is the output array

Array
(
    [0] => 4
    [2] => 400
    [3] => 4000
    [4] => 40000
)

from the above array i need to replace the key in an orderly manner.

Array
(
    [0] => 4
    [1] => 400
    [2] => 4000
    [3] => 40000
)

then, I need to add 2 values into above array. That values should any of the the values that array contain. Finally, i need the output like this

Array
(
    [0] => 4
    [1] => 400
    [2] => 4000
    [3] => 40000
    [4] => 40
    [5] => 4000
)

How to do this?

2 Answers 2

5
//replace the key orderly
$new_array = array_values($old_array);
//add value
$new_array[] = $new_value; 
Sign up to request clarification or add additional context in comments.

Comments

0

Not sure what you are trying to do, but it seems that you need to grab a random key twice after you corrected the array keys:

$arr=array ( 0 => 4, 2 => 400, 3 => 4000, 4 => 40000 );
echo "Before the array keys are sorted orderly:<br/>";
echo "<pre>";
print_r($arr);
echo "</pre>";

$arr = array_values($arr);

for($i=0; $i<2; $i++)
{
    $array_size=count($arr);
    $arr[]=$arr[mt_rand(0, $array_size-1)];
}
echo "After the sort and added values:<br/>";
echo "<pre>";
print_r($arr);
echo "</pre>";

Copy and paste this code and run it and see if it produces the desired result.

EDIT - EDIT - EDIT

Please elaborate on the last step:

then, I need to add 2 values into above array. That values should any of the the values that array contain. Finally, i need the output like this

My questions:

  1. Can you put any value in the array or just the values that you already have in the array? The last 2 indexes contain the values "40" and "4000", but there is no 40 value in the whole array.

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.