0

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
)

3 Answers 3

2

Try like

foreach($array2 as $key => $value) {
   $temp = array_key_exists($value, $array2) ? $array1[$value] : 0;
   $newArr[$key] = $temp;
}
Sign up to request clarification or add additional context in comments.

4 Comments

This needs improvement desperately. For one it will produce null instead of zeroes, and it will also emit notices. Don't use code like this.
@Jon sorry for late.Actually I realized after I submit my ans.Thanks for the suggestion
@Gautam3164: Ok, but why also change $array1 in the process?
@Jon ;-) .Ok edited.Just a glance that I considered his need.I think no need other than that.
2

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);

Comments

0

Try

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

See demo here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.