0

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") .

2

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

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.