Matheus Isac
Matheus Isac

Reputation: 25

how to add new values ​to the array by taking the existing values ​and adding data to the end of each value

I have an array with the values ​​$arr = array ("1.", "2.") and would like to add new values ​​to this array where the new values ​​will be the existing values ​​with an added value.

Example: $arr = array("1.", "2.") should transforms into $arr = array ("1.", "2.", "1.1", "2.1") .

Upvotes: 0

Views: 39

Answers (2)

Sadegh Ameri
Sadegh Ameri

Reputation: 310

I recommend a for loop

<?php
$arr = array("1.","2.");
$length = count($arr);
for($i=0; $i<$length; $i++)
    $arr[] = $arr[$i] . '1';
var_dump($arr);

Hope that helps :)

Upvotes: 1

Jakub Kisielewski
Jakub Kisielewski

Reputation: 46

Functional approach:

<?php

$input = ['1.', '2.'];
$append = '1';

$out = array_merge(
    $input,
    array_map(function(string $val) use ($append) {
        return $val . $append;
    }, $input)
);

var_dump($out);

Run it live: https://3v4l.org/TeRvN

How it works: It takes the input array (values '1.' and '2.'), adds the $append to each array element and merges with the original array.

Upvotes: 1

Related Questions