Search code examples
phparraysindexingindices

PHP: Set index array based on other array


I have the following two hypothetical arrays:

$values = array("fourth", "first", "second", "third");
$indices = array(3, 0, 1, 2);

What is the fastest way to rearrange $values based on $indices?

Is there perhaps some way to do $values->index_array = $indices?


Solution

  • I'd do:

    <?php
    $newarray = array_fill_keys($indices, $values);
    ?>
    

    This assumes your indices are always unique of course.