How to combine array values ​​and individual constants without using foreach?

I am trying to find an easier way to create new arrays from existing arrays and values. There are two procedures that I would like to optimize, similar in design. Form one:

$i = 0;
$new_array = array();
foreach ($my_array as $value) {                 
    $new_array[$i][0] = $constant;  // defined previously and unchanging
    $new_array[$i][1] = $value;     // different for each index of $my_array
    $i++;
}

The second form has not one, but two different values ​​per constant; note that $ is before $ key in indexing:

$i = 0;
$new_array = array();
foreach ($my_array as $key => $value) {                 
    $new_array[$i][0] = $constant;  // defined previously and unchanging
    $new_array[$i][1] = $value;     // different for each index of $my_array
    $new_array[$i][2] = $key;   // different for each index of $my_array
    $i++;
}

Is there a way to optimize these procedures with shorter and more efficient routines using PHP array operators? (There are many, of course, and I cannot find one that seems to fit the bill.)

+4
source share
5 answers

, Wouter Thielen, , .

:

$new_array = array();
// $my_array is numeric, so $key will be index count:
foreach ($my_array as $key => $value) { 
    $new_array[$key] = array($constant, $value);
};

:

// $my_array is associative, so $key will initially be a text index (or similar):
$new_array = array();
foreach ($my_array as $key => $value) { 
    $new_array[$key] = array($constant, $value, $key);
};
// This converts the indexes to consecutive integers starting with 0:
$new_array = array_values($new_array);
+1

, $i-counter

$new_array = array();
foreach ($my_array as $key => $value) {                 
    $new_array[$key][0] = $constant;  // defined previously and unchanging
    $new_array[$key][1] = $value;     // different for each index of $my_array
}
0

- array_push, :

 $new_array = array();
            foreach ($my_array as $key => $value) { 
            $new_array[$key] = array();
            array_push($new_array[$key],$constant,$value,$key);                   
            };

array_merge:

$new_array = array();
                foreach ($my_array as $key => $value) { 
                $new_array[$key] = array_merge((array)$constant,(array)$value,(array)$key);           
                };
0

array_map:

$new_array = array_map(function($v) use ($constant) {
    return array($constant, $v);
}, $my_array);

, :

$new_array = array_map(function($k, $v) use ($constant) {
    return array($constant, $v, $k);
}, array_keys($my_array), $my_array);

, $constant , use ($constant) .

array_walk , , , , $my_array, array_walk. :

array_walk($my_array, function(&$val, $key) use($constant) {
    $val = array($constant, $val, $key);
});

, , (.. , ). , array_values:

$numerically_indexed = array_values($associative);
0

All Articles