user1906399
user1906399

Reputation: 771

How do i properly add an element into an array depending on the elements have values or not in php

I'm trying to do something as below :

$location1 = (isset($_POST['location1'])) ? $_POST['location1'] : null ;
$location2 = (isset($_POST['location2'])) ? $_POST['location2'] : null ;
$locations = array($location1, $location2);

print_r($locations);

here print_r($locatios) showing Array ( [0] => location1 [1] => ) , an unnecessary index is being created if $location2 is null. I want if $location2 is null then i get just Array ( [0] => location1)

Upvotes: 0

Views: 42

Answers (4)

deceze
deceze

Reputation: 522032

Name your form inputs with []:

<input name="locations[]">
<input name="locations[]">

Then you're already getting them as needed:

$locations = $_POST['locations'];

Optionally: filter out empty submitted fields:

$locations = array_filter($_POST['locations']);

Upvotes: 1

Tim Lewis
Tim Lewis

Reputation: 29258

$locations = array();

if(isset($_POST['location1']) {
    array_push($locations, $_POST['location1']);
}

if(isset($_POST['location2']) {
    array_push($locations, $_POST['location2']);
}

print_r($locations);

Your logic was still inputting null into the array, which is why that index is there.

Upvotes: 1

marian0
marian0

Reputation: 3327

I think if statement will be better in this case.

$locations = array();

if (isset($_POST['location1'])) {
    $locations[] = $_POST['location1'];
}

if (isset($_POST['location2'])) {
    $locations[] = $_POST['location2'];
}

Upvotes: 3

Scott
Scott

Reputation: 3765

Try an array_merge:

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

So:

 $locations = array_merge($location1, $location2);

And this question deals with the issue when one of the arrays is empty: PHP array_merge if not empty

By checking if it's array first before merging:

 if(is_array($location1)) {

Upvotes: 0

Related Questions