AbsoluteBeginner
AbsoluteBeginner

Reputation: 2255

PHP $_POST array

I'm building a webhook that will receive data from an external service.

In order to retrieve data, I'm using the following array:

$data = [
$_POST['aaa'],
$_POST['bbb'],
$_POST['ccc'],
$_POST['ddd'],
$_POST['eee']
];

Is it possible to build the same array without repeating $_POST? I mean something like:

$data = $_POST [
['aaa'],
['bbb'],
['ccc'],
['ddd'],
['eee']
];

Obviously, that code is wrong.

Thanks.

Upvotes: 0

Views: 104

Answers (3)

Christoff X
Christoff X

Reputation: 111

The simplest way for me would be:

  1. For getting all the values in the $_POST array

foreach($_POST as $value){ $data[] = $value; }

  1. For getting all the values and want to keep the key

foreach($_POST as $key=>$value){ $data[$key] = $value; }

  1. For getting a specific array of values from the array

foreach(['aaa','bbb','ccc','ddd','eee'] as $column){ $data[] = $_POST[$column]; }

  1. Just a good idea to always escape variables ;)

$con = mysqli_connect('hostcleveranswer.com','USERyouearn','PWDanupv0Te','dropthemicDB') foreach($_POST as $key => $value) { $data[] = mysqli_escape_string($con,$value); }

//i feel that was a good simple answer using tools without having to a learn a new function syntax

Upvotes: 0

NastyStyles
NastyStyles

Reputation: 54

$data = $_POST

This will build your new $data array the same way as your GLOBAL $_POST array including the POST Key names and their assigned values.

Also checkout extract($_POST), as this will extract each key to its same name variable, which may be easier to then reference in your web-hook or any functions or procedural code you uses from then on. This essentially does this:

$aaa = $POST['aaa']
$bbb = $POST['bbb']
$ccc = $POST['ccc']

etc etc https://www.php.net/manual/en/function.extract.php

Upvotes: 0

Barmar
Barmar

Reputation: 780688

There's no shortcut like that. You could use array_map():

$data = array_map(function($key) {
    return $_POST[$key];
}, ['aaa', 'bbb', 'ccc', ...]);

Upvotes: 1

Related Questions