Basith
Basith

Reputation: 1075

Check an array value exists another array key in PHP

I have two arrays with the following values,

First Array:

Array
(
    [Strongly Agree] => 100
)

Second Array:

Array
(
    [0] => Strongly Agree
    [1] => Agree
    [2] => Neither Agree or Disagree
    [3] => Strongly Disagree
)

I need the output should like this,

Array (
        [0] => 100
        [1] => 0
        [2] => 0
        [3] => 0
)

Upvotes: 0

Views: 55

Answers (3)

Nouphal.M
Nouphal.M

Reputation: 6344

Try

$arr2 = array_merge(array_fill_keys($arr2, 0), $arr1);

See demo here

Upvotes: 0

GautamD31
GautamD31

Reputation: 28763

Try like

foreach($array2 as $key => $value) {
   $temp = array_key_exists($value, $array2) ? $array1[$value] : 0;
   $newArr[$key] = $temp;
}

Upvotes: 2

ffflabs
ffflabs

Reputation: 17481

array key exists won't trigger notices

$sample = array('Strongly Agree' => 100);
$alternatives = array(   'Strongly Agree',    'Agree',    'Neither Agree or Disagree',    'Strongly Disagree');
$output=array();
foreach($alternatives as $alternative) {
    $output[$alternative] = array_key_exists($alternative, $sample)? $sample[$alternative]:0;
}

print_r($output);

Upvotes: 2

Related Questions