Vivek Srivastava
Vivek Srivastava

Reputation: 33

I want to add an element to an array at random postion using a loop

I want to add an element to an array at random postion using a loop

I have a fixed ranks like the following

$ranks=array("10","9","8","7","6","5","4","3","2","1");

And I have a random rank position according to a chain,

$agent_ranks=array("10","6","2","1");

which are missing indices

I have calculated the difference between the arrays

$arr_diff=array("9","8","7","5","4","3");

Now I want a dynamic array as a result:

$arr_diff_new=array("0","9","8","7","0","5","4","3","0","0");

How can I add value="0" at the missing indices?

Upvotes: 3

Views: 74

Answers (5)

Narendrasingh Sisodia
Narendrasingh Sisodia

Reputation: 21437

Simply using in_array with foreach loop like as

$ranks=array("10","9","8","7","6","5","4","3","2","1");
$agent_ranks=array("10","6","2","1");
$result = array();
foreach($ranks as $key => $value){
    $result[] = in_array($value,$agent_ranks) ? 0 : $value;
}
print_r($result);

Upvotes: 0

Hardik Solanki
Hardik Solanki

Reputation: 3195

You can do it using in_array and for loop:

$ranks=array("10","9","8","7","6","5","4","3","2","1");
$agent_ranks=array("10","6","2","1");

for($i=0;$i < count($ranks); $i++){
    if(in_array($ranks[$i], $agent_ranks)){
        $newarray[$i] = 0;
    }else{
        $newarray[$i] = $ranks[$i];
    }
}
print_r($newarray);

Upvotes: 0

Rogin Thomas
Rogin Thomas

Reputation: 772

You can use array function array_map,

<?php
$array1=array("10","9","8","7","6","5","4","3","2","1");
print_r(array_map('filter',$array1));
function filter($a){
 $array2=array("9","8","7","5","4","3");
 if(in_array($a,$array2)){
    return $a;
 }else{
    return 0;
 }
}

?>

Upvotes: 0

Gvidas
Gvidas

Reputation: 1964

You can also use in_array in if clause to check if rank is int $agent_ranks and then push 0 or old rank value to new array

$arr_diff_new = array();
foreach($ranks as $rank){
    array_push($arr_diff_new,(in_array($rank,$agent_ranks))?0:$rank);
}

Upvotes: 0

VolkerK
VolkerK

Reputation: 96159

<?php
$ranks=array("10","9","8","7","6","5","4","3","2","1");
$agent_ranks= array_flip( array("10","6","2","1") );

foreach( $ranks as $k=>$v ) {
    if ( isset($agent_ranks[$v]) ) {
        $ranks[$k] = 0;
    }
}

var_export($ranks);

prints

array (
  0 => 0,
  1 => '9',
  2 => '8',
  3 => '7',
  4 => 0,
  5 => '5',
  6 => '4',
  7 => '3',
  8 => 0,
  9 => 0,
)

see also: array_flip

Upvotes: 3

Related Questions