3

I am trying to create a function with will do the following: There is an array built in the form of

$array = [
    0 => 1,
    1 => 2,
    2 => 4,
];

i want to create a string in the length of 5, in which the values of the current array in the correct order, like: 12040.

or

$array = [
    0 => 3,
    1 => 5,
];

will become: 00305

essentially, replacing the places that don't exist in the array with 0 in the string.

thank you!

3
  • 3
    How does: [1,2,4] become 1204 and [3,5] -> 00305 ? I don't see the pattern behind it Commented Dec 1, 2015 at 15:06
  • confusing....what do you want to achieve? Commented Dec 1, 2015 at 15:10
  • 2
    @Rizier123 it looks like the 0s are where the value does not exist - ie. [1,2,4] is missing the 3,5, so they want to do [1,2,0,4,0] or 12040, and [0,0,3,0,5]/00305 since the 1,2,4 are not set Commented Dec 1, 2015 at 15:13

2 Answers 2

3

Something like this should be what you are looking for:

<?php
$input = [1,2,5,6,8];
$string = '';
for ($i=1; $i<=max($input); $i++) {
    $string .= in_array($i, $input) ? $i : '0';
}
var_dump($string);

The output is:

string(8) "12005608"
Sign up to request clarification or add additional context in comments.

1 Comment

+1. However, this assumes that the highest number in the array is the last number of the string. Whereas, in the first example given in the question, the string also "checks" for the number 5, which is not present in the array.
2

I'm not 100% certain I understood what you meant, but I think you are looking for this:

$finalString = "";
for ($i = 0, $j = count($myArray); $i < $j; $i++)
{
    if (isset($myArray[$i]))
    {
        $finalString .= $myArray[$i];
    }
    else
    {
        $finalString .= "0";
    }
}

EDIT: I realised you are probably looking for this:

$myArray = [3, 5];
$finalString = "";
for ($i = 1; $i <= 5; $i++)
{
    if (in_array($i, $myArray))
    {
        $finalString .= $i;
    }
    else
    {
        $finalString .= "0";
    }
}

After this $finalString contains 00305. If you want to continue this further than just 5 spaces, just change the 5 in the loop.

1 Comment

Personally I'd prefer arkascha's solution in production code. I wrote it like this to make it clear and understandable for the OP. One important difference: arkascha's solution never will create a string longer than the highest value in the array. So you'd never get trailing 0's. So with [2] as input you'd get 02 back, not 02000.

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.