简体   繁体   中英

insert value in array PHP

im new in PHP. just a simple question :

Coding :

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

i want value $b that "true" add to new array.

thanks.

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

只需使用array_push()

array_push($array, "true");
  1. Define the array.

  2. Push the data into the array.

Example:

$array = new array();

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

use array_push check this link

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

We can add to a numerical array in these ways:

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

You can also push values to an array:

$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

You can also add to array by directly setting the index:

$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

Use it:

array_push($arr,"true");

or

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

To know more about array_push read this :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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