5

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.

2
  • 2
    To which array? Create some right before foreach Commented Jul 11, 2012 at 4:51
  • Use array_splice. Commented Jul 11, 2012 at 4:54

5 Answers 5

8
$arr = array();
foreach($group as $b) {
    if ($b == 0) {
        echo "error";
    } else {
        echo "true";
        $arr[] = $b;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

Simply use array_push().

array_push($array, "true");

1 Comment

i want to add value $b into array. array_push($new_array, $b); am i right?
2
  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?
    }
}

Comments

1

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

1 Comment

Use $arr[] instead of array_push() - it's faster.
1

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

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.