I converted an old cgi mailform form to PHP by simply doing the below and emailing $msg as the body of the email.
I'd like to extract the value of the field "email" as a seperate variable to use as the reply-to address.
foreach ($_POST as $field=>$value) {
if ($field != "submit") $msg .= $field . ": " . $value . "\n";
}
will something like $field[email] have the value of the email field in it?
This will do it if you're working with a single dimension array. If you have an associative array, then you'll need to add another search variable. An associative could look something like:
Array (1) (
Array (3) (
["email"] =>
[0] => jointtech#example.com
[1] => bob#example.com
[2] => tom#example.com
)
)
foreach ($_POST as $field=>$value) {
if ( strpos($field, 'submit') === false ) {
$msg .= $field['email'] . ": " . $value . "\n";
}
If you have the associative array above, then the $field['email'] will not work.
Related
I have an object $userStatus which is fetching the values in the following format via an API call.
I am unable to allocate the values via loop.
foreach($usersStatus as $user => $element) {
print "[".$user."] => ". $element ."<br />";
}
The following script in php allows me to print the first set of values until the key ["total_time"] => String96) "6m 34s" but then I get a following warning
Warning: Array to string conversion in C:\XAMPP\htdocs\Check-status.php on line 119
[units] => Array
Is there a way, I can traverse the whole object including the two arrays [0][1] using a loop and assign any value to any variable.
I know vardump will print the whole thing, but I want to traverse the whole object via loop or nested loops.
["role"]=>string(7) "learner"
["enrolled_on"]=>string(20) "05/01/2021, 17:44:53"
["enrolled_on_timestamp"]=>string(10) "1609868693"
["completion_status"]=>string(9) "Completed"
["completion_percentage"]=>string(3) "100"
["completed_on"]=>string(20) "06/01/2021, 16:58:23"
["completed_on_timestamp"]=>string(10) "1609952303"
["expired_on"]=>string(0) ""
["expired_on_timestamp"]=>NULL
["total_time"]=>string(6) "6m 34s"
["units"]=>array(2) {
[0]=>array(8) {
["id"]=>string(4) "2047"
["name"]=>string(26) "MyCourse1 2019"
["type"]=>string(19) "SCORM | xAPI | cmi5"
["completion_status"]=>string(9) "Completed"
["completed_on"]=>string(20) "06/01/2021, 16:58:23"
["completed_on_timestamp"]=>string(10) "1609952303"
["score"]=>NULL
["total_time"]=>string(6) "3m 56s"
}
[1]=>array(8) {
["id"]=>string(4) "2059"
["name"]=>string(34) "Assessment - MyCourse1"
["type"]=>string(4) "Test"
["completion_status"]=>string(9) "Completed"
["completed_on"]=>string(20) "06/01/2021, 15:06:56"
["completed_on_timestamp"]=>string(10) "1609945616"
["score"]=>string(5) "91.67"
["total_time"]=>string(6) "2m 38s"
}
}
Thank you for your help!
Check if $element is array to avoid this
foreach($usersStatus as $user => $element) {
// check if the value is not array
if (!is_array($element)) {
print "[".$user."] => ". $element ."<br />";
} else {
// value is array do with it whatever you want
// like another foreach for example
foreach($element as $key => $value) {
// do whatever
}
}
}
array_walk_recursive will satisfy your example. It will apply a user function to every member of an array while recursively doing so if the type is an array.
array_walk_recursive($arr, function ($val, $key) {
echo "[" . $key . "] => " . $val . "<br />";
});
I have written a code, that finds value in second array if it finds specific key from first array, but my question is - is it possible to do it better? for example without 3 loops ?
For example here are keys and values to search for, which user has checked at form and submitted ($tegoszukamy):
array (
'kolor' =>
array (
0 => 'bialy',
1 => 'zielony',
),
'rozmiar' =>
array (
0 => '60',
1 => '70',
),
'rozdzielczość' =>
array (
0 => '1200x1800',
),
'moc' =>
array (
0 => '500W',
),
);
Here is array with products IDs where searching is performed ($tuszukamy):
array (
47 =>
array (
'rozmiar' => '50,60,70,80,90,100',
'kolor' => 'bialy,czarny',
),
48 =>
array (
'rozmiar' => 'L,M,XS,S,L',
'kolor' => 'zielony,niebieski,czerwony,zolty,bialy,czarny',
),
49 =>
array (
'rozdzielczość' => '1200x1800',
'prędkość' => '60str/min',
)
)
Here is my code that is working fine:
foreach ($tegoszukamy as $atrybut=>$wartosci_szukane) {
foreach ($tuszukamy as $numer_posta=>$wartosci_zbioru ) {
if (array_key_exists($atrybut, $wartosci_zbioru) !== FALSE){
foreach ($wartosci_szukane as $ws) {
if (strpos($wartosci_zbioru[$atrybut],$ws) !== FALSE) {
echo
'We have found'
.$ws.
'in'
.$wartosci_zbioru[$atrybut].
'where product id is'
.$numer_posta.
''
;}
else {
echo
'We found not'
.$ws.
'in'
.$wartosci_zbioru[$atrybut].
''
;}
}
}
}
}
Is it possible to do it better/with better code performance/speed, because I dont know if these 3 loops will be good when user filters through eg. 10000 products.
I came up with the following alternatives:
1.
class Subject {
private $attr_name;
private $attr_values;
function __construct($attr_name, $attr_values) {
$this->attr_name = $attr_name;
$this->attr_values = $attr_values;
}
public function check($key, $item) {
$found = array();
if (isset($item[$this->attr_name])) {
foreach($this->attr_values as $val) {
strstr($item[$this->attr_name], $val) && array_push($found, $val);
}
}
count($found) > 0 ?
$message = "Found attribute <u>" . $this->attr_name . "</u> with value <b>" . implode(", ", $found) . "</b> in ID: " . $key . "."
:
$message = "No matches for <u>" . $this->attr_name . "</u> found in ID: " . $key;
return $message;
}
}
foreach ($tegoszukamy as $attr_name=>$attr_values) {
$filtered = array_map(array(new Subject($attr_name, $attr_values), "check"), array_keys($tuszukamy), $tuszukamy);
foreach($filtered as $result) {
echo $result . '<br>';
}
}
2.
foreach ($tegoszukamy as $attr_name=>$attr_values) {
$filtered = array_filter($tuszukamy, function ($item, $key) use($attr_name, $attr_values) {
$found = array();
if (isset($item[$attr_name])) {
// var_dump($item[$attr_name]);
foreach($attr_values as $val) {
strstr($item[$attr_name], $val) && array_push($found, $val);
}
}
count($found) > 0 ?
$message = "Found attribute <u>" . $attr_name . "</u> with value <b>" . implode(", ", $found) . "</b> in ID: " . $key . "."
:
$message = "No matches for <u>" . $attr_name . "</u> found in ID: " . $key;
echo $message . "<br>";
return count($found) > 0;
}, ARRAY_FILTER_USE_BOTH);
// something to do with $filtered;
}
I'm not sure whether either of them is faster than yours. I'll leave the testing to you. :)
The first one was inspired by jensgram's answer to this question: PHP array_filter with arguments
I am pulling elements from a standard class object into an assoc array like so:
$array = $subjects;
foreach ( $array as $subject ) {
foreach ( $subject as $prop => $val ) {
if ( $val !== '' ) {
echo $prop . ' = ' . $val;
echo "<br>";
}
}
}
I get the result I expect from above, except what I'd like to do is echo out individual values into a table.
When I do this:
echo $subject['day1'];
I get this: "Cannot use object of type stdClass as array."
Where am I going wrong? Thanks in advance.
If it's using StdClass you'll need to do this:
$subject->day1
If you want to convert it to an array, have a look at this question: php stdClass to array
You are trying to iterate over the $array and $array is still an object. Use this:
$vars = get_object_vars($subjects);
to get assoc. array from the object $subjects. Then go:
foreach ($vars as $name => $value) {
echo $name . "=" . $value;
echo "<br>";
}
I have form with several fields I want to store those values in a session variable. Some of those fields should be 0 if the user doesn't fill them in.
A print_r($_POST) after submitting the form shows:
[report] => Array
(
[a_name] => Array
(
[0] =>
)
[a_id_card] => Array
(
[0] =>
)
[a_total] =>
Yet, after running the following PHP code, it seems that "a_name" and "a_id_card" are not interpreted as arrays. Any ideea why?
if (isset($_POST['submit'])) {
foreach ($_POST as $key => $value) {
if (!is_array($key) && trim($value) == '') {
$value = 0;
$_SESSION['report'][$key] = $value;
} else {
$_SESSION['report'][$key] = $value;
}
}
}
think you want to write this - is_array($value)
$key is the string 'report'. So is_array($key) == false. However $_POST[$key] or $value is an array.
The key is never an array. It is always a scalar or string. The value, on the other hand, can be an array.
Maybe you want look only $_POST['report'], and check if 'value' is or not an array (not key):
if (isset($_POST['submit'])) {
foreach ($_POST['report'] as $key => $value) {
if (!is_array($value) && trim($value) == '') {
$value = 0;
$_SESSION['report'][$key] = $value;
} else {
$_SESSION['report'][$key] = $value;
}
}
}
i'm using sirportly for my support and i have the ability to post forms remotely via html, however i'm trying to integrate this into wordpress and so want to post this form from a plugin via curl/php the challenge i am having is to post into array objects:
eg the basic original HTML form generated by sirportly contains the following:
<input type='text' name='ticket[name]' id='form26-name' />
<input type='text' name='ticket[email]' id='form26-email' />
<input type='text' name='ticket[subject]' id='form26-subject' />
<textarea name='ticket[message]' id='form26-message'></textarea>
i know for basic form elements eg name=name, name=email etc i can do the following:
//create array of data to be posted
$post_data['firstName'] = 'Name';
$post_data['action'] = 'Register';
//traverse array and prepare data for posting (key1=value1)
foreach ( $post_data as $key => $value) {
$post_items[] = $key . '=' . $value;
}
//create the final string to be posted using implode()
$post_string = implode ('&', $post_items);
how do i do similar given that the elements need to be posted as 'ticket[name]' rather than just 'name'
EDIT/UPDATE - ANSWER
thanks to the answers below i came up with the solution, my issue wasn't getting access to the data from the array as i was recieving it a different way (but from an array all the same), but correctly encoding it in the post request, here is what i ended up with(note that i'm using gravity forms to get the data:
//numbers in here should match the field ID's in your gravity form
$post_data['name'] = $entry["1"];
$post_data['email'] = $entry["2"];
$post_data['subject'] = $entry["3"];
$post_data['message']= $entry["4"];
foreach ( $post_data as $key => $value) {
$post_items[] = 'ticket[' . $key . ']' . '=' . $value;
}
$post_string = implode ('&', $post_items);
i just had to change the for loop to wrap the extra ticket[ and ] parts around the key for the post submission
foreach ( $post_data['ticket'] as $key => $value) {
$post_items[] = $key . '=' . $value;
}
The form you listed above will result in this structure on server:
$_POST["ticket"] = Array(
"name" => "some name",
"email" => "some#thing",
"subject" => "subject of something",
"message" => "message text"
);
So, $_POST["ticket"] is really your $post_data
You access the variable by this: $_POST['ticket']['name']
so if you want to see the value you should: echo $_POST['ticket']['name'];
to loop you go:
foreach($_POST['ticket'] as $key => $val){
echo "Key => " . $key. ", Value => " . $val . "<br />";
}