PHP, combine two arrays into a new array, using the first array's values as the keys

Asked
Active3 hr before
Viewed126 times

6 Answers

valuesarrayarrays
90%

I have two arrays I want to combine. I need to take the values from the first array, use these values as the keys to match from the second array, and combine them into a third array (the one I'll use)., Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers ,The first argument is the array of your fast food restaurants, the second argument is the first array you gave (the keys you want),Please be sure to answer the question. Provide details and share your research!

Here's a simple imperative solution:

$combined = array();

foreach($array1 as $v) {
   if (isset($array2[$v])) {
      $combined[$v] = $array2[$v];
   }
}

And a functional solution:

// Note that elements of $combined will retain the order of $array2, not $array1
$combined = array_intersect_key($array2, array_flip($array1));
load more v
88%

Creates an array by using the values from the keys array as keys and the values from the values array as the corresponding values. ,array_combine — Creates an array by using one array for keys and another for its values,array_values() - Return all the values of an array, Array of keys to be used. Illegal values for key will be converted to string.

Array
   (
      [green] => avocado[red] => apple[yellow] => banana
   )
72%

$output = array_merge($array1, $array2);
load more v
65%

Checking Existence of Keys,Take a value from an array,A key-value pair of desired array key name and model column name to take value from.,Name of array key or object property to retrieve value from.

Retrieving values from an array, an object or a complex structure consisting of both using standard PHP is quite repetitive. You have to check if key exists with isset first, then if it does you're getting it, if not, providing default value:

class User {
   public $name = 'Alex';
}

$array = [
   'foo' => [
      'bar' => new User(),
   ]
];

$value = isset($array['foo']['bar'] - > name) ? $array['foo']['bar'] - > name : null;
load more v
75%

First, the array_map() returns a new array with each element’s underscore string (_) replaced by the space.,The $separator is the separator that separates between two strings. The $separator defaults to an empty string.,Second, the implode() joins the strings of the returned array of the array_map() function.,The implode() function returns a new string resulting from joining string elements in the $array with the separator.

The PHP implode() function allows you to join an array of strings by a separator. Here’s the syntax of the implode() function:

.wp - block - code {
      border: 0;
      padding: 0;
   }

   .wp - block - code > div {
      overflow: auto;
   }

   .shcb - language {
      border: 0;
      clip: rect(1 px, 1 px, 1 px, 1 px); -
      webkit - clip - path: inset(50 % );
      clip - path: inset(50 % );
      height: 1 px;
      margin: -1 px;
      overflow: hidden;
      padding: 0;
      position: absolute;
      width: 1 px;
      word - wrap: normal;
      word - break: normal;
   }

   .hljs {
      box - sizing: border - box;
   }

   .hljs.shcb - code - table {
      display: table;
      width: 100 % ;
   }

   .hljs.shcb - code - table > .shcb - loc {
      color: inherit;
      display: table - row;
      width: 100 % ;
   }

   .hljs.shcb - code - table.shcb - loc > span {
      display: table - cell;
   }

   .wp - block - code code.hljs: not(.shcb - wrap - lines) {
      white - space: pre;
   }

   .wp - block - code code.hljs.shcb - wrap - lines {
      white - space: pre - wrap;
   }

   .hljs.shcb - line - numbers {
      border - spacing: 0;
      counter - reset: line;
   }

   .hljs.shcb - line - numbers > .shcb - loc {
      counter - increment: line;
   }

   .hljs.shcb - line - numbers.shcb - loc > span {
      padding - left: 0.75 em;
   }

   .hljs.shcb - line - numbers.shcb - loc::before {
      border - right: 1 px solid #ddd;
      content: counter(line);
      display: table - cell;
      padding: 0 0.75 em;
      text - align: right; -
      webkit - user - select: none; -
      moz - user - select: none; -
      ms - user - select: none;
      user - select: none;
      white - space: nowrap;
      width: 1 % ;
   }
implode(string $separator, array $array): stringCode language: PHP(php)
load more v
40%

To assign multiple values to an array in one step, use array():,Of course, you can mix and match numeric and string keys in one array() definition, but it’s confusing and very rarely needed:,You want to assign multiple elements to an array in one step, but you don’t want the first index to be 0.,To sort multiple arrays simultaneously, pass multiple arrays to array_multisort():

To assign multiple values to an array in one step, use array():

$fruits = array('Apples', 'Bananas', 'Cantaloupes', 'Dates');

array() is very handy when you have a short list of known values. The same array is also produced by:

$fruits[0] = 'Apples';
$fruits[1] = 'Bananas';
$fruits[2] = 'Cantaloupes';
$fruits[3] = 'Dates';

and:

$fruits[] = 'Apples';
$fruits[] = 'Bananas';
$fruits[] = 'Cantaloupes';
$fruits[] = 'Dates';

As of PHP 5.4, you can also use the short array syntax, inspired by JavaScript:

$fruits = ['Apples', 'Bananas', 'Cantaloupes', 'Dates'];

So far, we’ve placed integers and strings only inside arrays. However, PHP allows you to assign any data type you want to an array element: booleans, integers, floating-point numbers, strings, objects, resources, NULL, and even other arrays. So you can pull arrays or objects directly from a database and place them into an array:

while ($row = mysqli_fetch_assoc($r)) {
   $fruits[] = $row;
}

while ($obj = mysqli_fetch_object($s)) {
   $vegetables[] = $obj;
}

To define an array using not integer keys but string keys, you can also use array(), but specify the key/value pairs with =>:

$fruits = array('red' => 'Apples', 'yellow' => 'Bananas',
   'beige' => 'Cantaloupes', 'brown' => 'Dates');

Now, the value of $fruits['beige'] is Cantaloupes. This is shorthand for:

$fruits['red'] = 'Apples';
$fruits['yellow'] = 'Bananas';
$fruits['beige'] = 'Cantaloupes';
$fruits['brown'] = 'Dates';

The short syntax works here, too:

$fruits = [
   'red' => 'Apples',
   'yellow' => 'Bananas',
   'beige' => 'Cantaloupes',
   'brown' => 'Dates'
];

Each array can only hold one unique value for each key. Adding:

$fruits['red'] = 'Strawberry';

overwrites the value of 'Apples'. However, you can always add another key at a later time:

$fruits['orange'] = 'Orange';

The easiest way to cycle though an array and operate on all or some of the elements inside is to use foreach:

$fruits = array('red' => 'Apples', 'yellow' => 'Bananas',
   'beige' => 'Cantaloupes', 'brown' => 'Dates');

foreach($fruits as $color => $fruit) {
   print "$fruit are $color.\n";
}

To break an array apart into individual variables, use list():

$fruits = array('Apples', 'Bananas', 'Cantaloupes', 'Dates');

list($red, $yellow, $beige, $brown) = $fruits;
load more v

Other "values-array" queries related to "PHP, combine two arrays into a new array, using the first array's values as the keys"