1

i have the following array

$block = array(
          **********,
          *****,
          **********,
          ***,
          ********);

Assuming max length of each array would be 10

I'm trying to insert new value in that array so my output would be as follows:

**********
*****00000
**********
***0000000
********00

So the following are my codes:

foreach($block as $key=>$newblock)
{
    $counter = 10 - strlen($newblock); 
    if ($counter > 0)
    {
      for($x=0; $x < $counter; $x++)
      {
          $block[$key] = implode("0",$newblock);
      }
    }
}

foreach($block as $x)
{
    print $x;
}

The codes seems not working..

3
  • try $block[$key].='0' instead of implode in loop, can you share current output? Commented Apr 13, 2016 at 4:47
  • if i assign $block[$key] = '0', it will replace the '*' to '0' instead add '0' value at the end of the array Commented Apr 13, 2016 at 4:51
  • its not ='0' its .='0' there is '.' operator to append. Commented Apr 13, 2016 at 4:52

2 Answers 2

1

Try this code

<?php
$block = array(
          '**********',
          '*****',
          '**********',
          '***',
          '********');

foreach($block as $key=>$newblock)
{
    $counter = 10 - strlen($newblock); 
    if ($counter > 0)
      for($x=0; $x < $counter; $x++)
          $block[$key] .= "0";
}

foreach($block as $x)
    print $x."<br/>";
?>

Output

**********
*****00000
**********
***0000000
********00
Sign up to request clarification or add additional context in comments.

1 Comment

Great that I could help, welcome to stackoverflow @Julie
1

This is very simple, use function str_pad($input,$length,$pad_string) read more about str_pad()

<?php 
$block = array('**********','*****','**********','***','********'); 
foreach($block as $key=>$val)
{
    echo str_pad($val,10,"0");
    echo "</br>";
}
?>

This will Output :

**********
*****00000
**********
***0000000
********00

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.