简体   繁体   English

将值插入数组

[英]Insert value to an array

i have the following array 我有以下数组

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

Assuming max length of each array would be 10 假设每个数组的最大长度为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.. 该代码似乎不起作用。

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

This is very simple, use function str_pad($input,$length,$pad_string) read more about str_pad() 这很简单,使用函数str_pad($input,$length,$pad_string)阅读有关str_pad()的更多信息

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

This will Output : 这将输出:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM