簡體   English   中英

在數組PHP中插入值

[英]insert value in array PHP

我是PHP新手。 只是一個簡單的問題:

編碼:

foreach($group as $b)
{
  if($b == 0){
       echo "error";
  }
  else{
        echo "true";
  }
}

我希望值$ b“true”添加到新數組。

謝謝。

$arr = array();
foreach($group as $b) {
    if ($b == 0) {
        echo "error";
    } else {
        echo "true";
        $arr[] = $b;
    }
}

只需使用array_push()

array_push($array, "true");
  1. 定義數組。

  2. 將數據推入陣列。

例:

$array = new array();

foreach ($group as $b) {
    if ($b == 0) {
       echo "error";
    } else {
    echo "true";
    array_push($array,$b) //or any value?
    }
}

使用array_push檢查此鏈接

 $a = new array();
array_push($a,"true");
print_r($a);

我們可以通過以下方式添加數值數組:

$arr = new array("true");    //Create the array & add the values
var_dump($arr);    //Print the contents of the array to screen

您還可以將值推送到數組:

$arr = new array();    //Create the array
array_push($arr, 'true');    //'Push' the value into the next available index
var_dump($arr);    //Print the contents of the array to screen

您還可以通過直接設置索引來添加到數組:

$arr = new array();    //Create the array
$arr[0] = 'true';    //'Set' index 0 to the value
var_dump($arr);    //Print the contents of the array to screen

用它:

array_push($arr,"true");

要么

echo "true";
$arr[] = $b;

要了解有關array_push的更多信息,請閱讀:

http://php.net/manual/en/function.array-push.php

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM