4

I want to implode the multi array inside the for loop.

$_POST['PprodName'];

In this $_POST['PprodName'] I have got a value as:

Array ( [0] => steel mj23 [1] => [2] => [3] => [4] => [5] => [6] => [7] => )

steel mj23 is my first product name.

Now I want to check if the element is empty according to their position. so I applied a for loop but don't know how to implode element's which are not empty.

I want to implode only those element which are not empty.

Here is my for loop.

for( $i=0; $i < count($_POST['PprodName']); $i++ ) {
                    if( !empty( $_POST['PprodName'][$i] ) ) {
                        print_r($_POST['PprodName'][$i]);
                    }
                }

3 Answers 3

8

You don't need a for loop. Simply filter all empty values with array_filter() out and then you can simply use implode(), like this:

echo implode(", ", array_filter($_POST['PprodName']));
Sign up to request clarification or add additional context in comments.

3 Comments

@WaseemAhmed No <- see the check mark to the left of my post. If you click on on this one you say that the answer solved your problem
@WaseemAhmed no ^ See my link above in the comments!
@Rizier123 but it says " Vote-Up requires 15 reputation "
0

try this way Online Demo

$data=Array ( 0 => "steel mj23", 1 =>'test' ,2 =>'', 3 =>'' ,4 =>"", 5 =>"", 6 =>"", 7 =>"" );
$result=Array();
foreach($data as $key=>$value)
{
    if(!empty($value))
       $result[]=$value;         
}
var_dump($result);

3 Comments

it also works fine bro. but i think the array_fileter() is the father of all problem( Checking empty array )
@WaseemAhmed You think array_filter() is better, but accept this answer?! You know that you can only accept one answer?!
@ Rizier123 ok. undo and done. sorry. i am new to stackoverflow
0
  <?php
    $array = array(
        'fruit1' => 'apple',
        'fruit2' => 'orange',
        'fruit3' => ' ',
        'fruit4' => ' ',
        'fruit5' => 'apple');

        for ($i = 0; $i <  count($array); $i++) {
        $key=key($array);
        $val=$array[$key];
        if ($val<> ' ') {
           echo $key ." = ".  $val ." <br> ";
           }
         next($array);
        }


     /* fruit1 = apple
    fruit2 = orange
    fruit5 = apple
    */
    ?>

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.