use implode in $_GET - php

I have some forms in my page like :
<form method="get">
Enter Your Firstname :<input type="text" name="t1" />
Enter Your Lastname :<input type="text" name="t2" />
<input type="submit" name="sb" />
</form>
so users will fill this form and i want to have values of this form separated with comma
for example
John,Smith
James,Baker
so here is my php code
if ( isset ($_GET['sb']))
{
$t_array = array("t1","t2");
foreach ( $t_array as $key )
{
echo implode(',' , $_GET[$key]);
}
}
When i try to do this , i got this error :
Warning: implode() [<a href='function.implode'>function.implode</a>]: Invalid arguments passed in PATH on line 24
i don't know why i can't use implode in $_GET or $_POST
so how can i solve this problem ?
P.S : i want to use array and implode in my page , please don't write about other ways

There is an error in your logic.
here is sample code that might help you:
$t_array = array($_GET['t1'], $_GET['t2']);
$imploded = implode(',', $t_array);
echo $imploded;
This will work.

You're calling implode on a value, not an array. This code
echo implode(',' , $_GET[$key]);
calls it on $_GET[$key], which is a string.
You are trying for implode($_GET);.

What you need is something like below, you don't actually need implode for this:
if ( isset ($_GET['sb']))
{
$t_array = array("t1","t2");
$result = '';
foreach ( $t_array as $key )
{
if ($result != '') $result .= ',';
$result .= $_GET[$key];
}
}

You can't impode strings...
Try something like this:
if ( isset ($_GET['sb']))
{
$t_array = array("t1","t2");
$arr = array();
foreach ( $t_array as $key )
{
$arr[] = $_GET[$key];
}
echo implode(',' , $arr);
}

Related

How to pass multiple urls from text fields into array

I am trying to enter multiple urls from text field as input, into array to extract some data.
Here's my code
<form method="post">
<textarea name="urls[]" cols="150" rows="15" value=""></textarea>
<input type="submit" value="Get URLs" />
</form>
if (isset($_POST['urls']) && !empty($_POST['urls'])) {
// fetch data from specified url
foreach($_POST['urls'] as $key => $value){
$data = array($value);
$r = multiRequest($data);
}
}
foreach ($r as $key => $url){
$res = preg_match_all( "/[a-z0-9]+[_a-z0-9\.-]*[a-z0-9]+#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})/i",
$url, $matches);
if($res) {
foreach(array_unique($matches[0]) as $email) {
echo $email . "<br />";
}
} else {
echo "No data found.";
}
unset($value);
Now if I enter single url,www.example1.com, if fetches the data (email). But if I enter more than one url in the form, it doesn't works (No data found).
If I define url in array manually
$data = array('www.example1.com', 'www.example2.com', 'www.example3.com');
I can extract the data (email).
How to do it for multiple entries?
If you delimit your urls by a line return, we can split and process them:
<form method="post">
<textarea name="urls" cols="150" rows="15" value=""></textarea>
<input type="submit" />
Omit the square brackets on the input name if we have one textarea. (Alternatively use many text inputs with the name attribute urls[], to get your input into an array.)
<?php
$urls = $_POST['urls'] ?? '';
$urls = preg_split('#\R#', $urls);
$emails = [];
foreach ($urls as $url)
{
$pattern = '/[a-z0-9]+[_a-z0-9\.-]*[a-z0-9]+#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,4})/i';
if (preg_match_all($pattern, $url, $matches))
{
foreach(array_unique($matches[0]) as $email) {
$emails[] = $email;
}
}
}
if(empty($emails)) {
echo 'No emails found.';
} else {
print implode('<br>', $emails);
}
The input:
http://example.com
mailto://foo#example.com
Will output:
foo#example.com
You're passing one value in $data array by this syntax $data = array($value);.
Replace $data = array($value);
with
$data = array();
$data[] = $value;
This will append each new value to the &data array.
Example
Also, you have one textarea, it means that the value(text input) of it comes into name=urls[] as a first value of array urls[]. In PHP you'll get one value.
If you want to separate inputted data you need to split it. For example, if you will write inputs comma separated, then you'll need to make explode(",",$_POST["urls"];) at least. By the way, change name="urls[]" to simply name="urls".
Use this code for retrieving inputs comma separated:
<form method="post">
<textarea name="urls" cols="150" rows="15" value=""></textarea>
<input type="submit" value="Get URLs" />
</form>
if (isset($_POST['urls']) && !empty($_POST['urls'])) {
// fetch data from specified url
$inputs = explode(",",$_POST["urls"]);
$data = array();
foreach($inputs as $key => $value){
$data[] = $value;
}
$r = multiRequest($data);
}
As I understood your multiRequest() function should process your $data array, put this line outside the foreach loop. If you won't you will process $data array each loop.
Note: inputs should be comma separated in this case(in textarea).

How not to echo a value if already in the input value?

I have some values in a custom field:
save_post = "1200"
Or it could be, since I need a list eventually:
save_post = "1200, 1460, 1334"
Now when I load the page, I get these values and I set them in an input field, and I also add the current value id from the current page:
$allPosts = $userPosts.", ".$postid;
Where $userPostsis the single value or the value list from the custom field, and $postid is the current page id I want to add.
The result is:
<input type="text" value="1200, 23138, 23138, 23138">
I would always get duplicate values each time I hit the update submit button as the page refreshes itself:
<form id="saveId" action="" method="POST" class="" autocomplete="off">
<input type="text" name="save_post_value" value="<?php echo $userPosts.", ".$postid; ?>">
<button type="submit" class="save_post btn btn-danger">Update</button>
</form>
How can I check if a value is already in the input and if so, don't echo it?
A way would be to have them in an Array and then output in the input field the unique array, not sure if there is a shorter way.
Trying:
$allPosts = array($userPosts.", ".$postid);
$allPosts = array_unique($allPosts);
<input type="text" name="save_post_value" value="<?php foreach ($allPosts as $value) { echo $value; } ?>">
Also:
$allPosts = array($userPosts.", ".$postid);
$allPosts = array_unique($allPosts);
$allPosts = explode(", ", $allPosts);
<input type="text" name="save_post_value" value="<?php echo $allPosts; ?>"
And tried with implode() too:
$allPosts = array($userPosts.", ".$postid);
$allPosts = array_unique($allPosts);
$allPosts = implode(", ", $allPosts);
<input type="text" name="save_post_value" value="<?php echo $allPosts; ?>"
This is very basic example, but I think that this can be useful for your needs:
<?php
// Input data
$userPosts = '19000, 23138, 23138';
$postid = '23138';
// With array
$userPosts = str_replace(' ', '', $userPosts);
if (empty($userPosts)) {
$a = array();
} else {
$a = explode(',', $userPosts);
}
$a = array_unique($a, SORT_STRING);
if (in_array($postid, $a) === false) {
$a[] = $postid;
}
$userPosts = implode(', ', $a);
echo 'Result using array: '.$userPosts.'</br>';
?>
UPDATE:
It is possible to use a function. Check for empty posts is made using empty().
<?php
function getUniquePosts($xposts, $xid) {
$xposts = str_replace(' ', '', $xposts);
if (empty($xposts)) {
$a = array();
} else {
$a = explode(',', $xposts);
}
$a = array_unique($a, SORT_STRING);
if (in_array($xid, $a) === false) {
$a[] = $xid;
}
$xposts = implode(', ', $a);
$xposts = ltrim($xposts, ",");
return $xposts;
}
$userPosts = '19000, 23138, 23138';
$postId = '23138';
echo getUniquePosts($userPosts, $postId).'</br>';
?>
Then when loading form you can try with this:
...
$a = array_unique($a, SORT_STRING);
...
update_user_meta($user_id, 'save_post', getUniquePosts($a, $user_id));
Here is my code on checking duplicate values after submission:
$userPosts = '19000, 23138, 23138';
$postid = '23138';
$pattern = "/(?:^|\W)".$postid."(?:$|\W)/";
if(preg_match($pattern, $userPosts, $matches))
{
print 'There is a duplicate '.rtrim($matches[0] , ",");
}
Basically I reuse Zhorov's variables but on his approach he put it in an array, and then check if that array contains the submitted value, mine is almost the same as his approach but instead of putting it in an array; I use regex to determine is the value existed in the string.

Retrieve post array values

I have a form that sends all the data with jQuery .serialize() In the form are four arrays qty[], etc it send the form data to a sendMail page and I want to get the posted data back out of the arrays.
I have tried:
$qty = $_POST['qty[]'];
foreach($qty as $value)
{
$qtyOut = $value . "<br>";
}
And tried this:
for($q=0;$q<=$qty;$q++)
{
$qtyOut = $q . "<br>";
}
Is this the correct approach?
You have [] within your $_POST variable - these aren't required. You should use:
$qty = $_POST['qty'];
Your code would then be:
$qty = $_POST['qty'];
foreach($qty as $value) {
$qtyOut = $value . "<br>";
}
php automatically detects $_POST and $_GET-arrays so you can juse:
<form method="post">
<input value="user1" name="qty[]" type="checkbox">
<input value="user2" name="qty[]" type="checkbox">
<input type="submit">
</form>
<?php
$qty = $_POST['qty'];
and $qty will by a php-Array. Now you can access it by:
if (is_array($qty))
{
for ($i=0;$i<size($qty);$i++)
{
print ($qty[$i]);
}
}
?>
if you are not sure about the format of the received data structure you can use:
print_r($_POST['qty']);
or even
print_r($_POST);
to see how it is stored.
My version of PHP 4.4.4 throws an error:
Fatal error: Call to undefined function: size()
I changed size to count and then the routine ran correctly.
<?php
$qty = $_POST['qty'];
if (is_array($qty)) {
for ($i=0;$i<count($qty);$i++)
{
print ($qty[$i]);
}
}
?>
try using filter_input() with filters FILTER_SANITIZE_SPECIAL_CHARS and FILTER_REQUIRE_ARRAY as shown
$qty=filter_input(INPUT_POST, 'qty',FILTER_SANITIZE_SPECIAL_CHARS,FILTER_REQUIRE_ARRAY);
then you can iterate through it nicely as
foreach($qty as $key=>$value){
echo $value . "<br>";
}
PHP handles nested arrays nicely
try:
foreach($_POST['qty'] as $qty){
echo $qty
}
I prefer foreach insted of for, because you do not need to heandle the size.
if( isset( $_POST['qty'] ) )
{
$qty = $_POST ['qty'] ;
if( is_array( $qty ) )
{
foreach ( $qty as $key => $value )
{
print( $value );
}
}
}

PHP how to split an array in variables

Hi everybody i need help! I've starting to learn php some week ago.
i have a form that POST some text field for a contact, i need to split the array in some variables to put in a email. this is my code
$field = $_POST['input'];
if ( isset( $field ) === TRUE){
foreach ($field as $key => $value) {
echo '<pre>' , print_r( $value ) , '</pre>'; //to list the array
}
$to = $mail;
$sbj = "thanks to register to $site";
..//some headers
mail($to,sbj,$headers)
}
and this is the form
<form action="upload.php" method="POST">
<input type="text" name="input[]">
<input type="text" name="input[]">
<input type="text" name="input[]">
<input type="submit" value="invia">
</form>
any suggestion for retrive the variables on the array to include on the mail?
#John has given the right procedure . You can use another procedure by using array_push() function eg:
$field = $_POST['input'];
$info = array();
foreach ($field as $key => $value) {
array_push($info,$value);
}
// echo implode(",",$info);
$to = $mail;
$sbj = "thanks to register to $site";
$body = implode(",",$info);
..//some headers
mail($to,sbj,$body,$headers)
You can use the implode() function , which takes an array and a separator and joins the elements of the array together into a string, with each element separated by the separator string you pass it eg:
foreach($field as $key=>$value) {
$input[] = $value;
}
$body = implode("\n",$input); //implode here
$to = $mail;
$sbj = "thanks to register to $site";
..//some headers
mail($to,sbj,$body,$headers)
This would create your list of input each on a separate line in the email.
the easiest, but most ugly way to to this is just using:
mail($to,sbj,print_r($field, true),$headers);
print_r($field, true) will output the value to a variable and not print it out immediately.

PHP | Get input name through $_POST[]

HTML example:
<form method="post" id="form" action="form_action.php">
<input name="email" type="text" />
</form>
User fills input field with: dfg#dfg.com
echo $_POST['email']; //output: dfg#dfg.com
The name and value of each input within the form is send to the server.
Is there a way to get the name property?
So something like..
echo $_POST['email'].name; //output: email
EDIT:
To clarify some confusion about my question;
The idea was to validate each input dynamically using a switch. I use a separate validation class to keep everything clean. This is a short example of my end result:
//Main php page
if (is_validForm()) {
//All input is valid, do something..
}
//Separate validation class
function is_validForm () {
foreach ($_POST as $name => $value) {
if (!is_validInput($name, $value)) return false;
}
return true;
}
function is_validInput($name, $value) {
if (!$this->is_input($value)) return false;
switch($name) {
case email: return $this->is_email($value);
break;
case password: return $this->is_password($value);
break;
//and all other inputs
}
}
Thanks to raina77ow and everyone else!
You can process $_POST in foreach loop to get both names and their values, like this:
foreach ($_POST as $name => $value) {
echo $name; // email, for example
echo $value; // the same as echo $_POST['email'], in this case
}
But you're not able to fetch the name of property from $_POST['email'] value - it's a simple string, and it does not store its "origin".
foreach($_POST as $key => $value)
{
echo 'Key is: '.$key;
echo 'Value is: '.$value;
}
If you wanted to do it dynamically though, you could do it like this:
foreach ($_POST as $key => $value)
{
echo 'Name: ', $key, "\nValue: ", $value, "\n";
}
Loop your object/array with foreach:
foreach($_POST as $key => $items) {
echo $key . "<br />";
}
Or you can use var_dump or print_r to debug large variables like arrays or objects:
echo '<pre>' . print_r($_POST, true) . '</pre>';
Or
echo '<pre>';
var_dump($_POST);
echo '</pre>';
Actually I found something that might work for you, have a look at this-
http://php.net/manual/en/function.key.php
This page says that the code below,
<?php
$array = array(
'fruit1' => 'apple',
'fruit2' => 'orange',
'fruit3' => 'grape',
'fruit4' => 'apple',
'fruit5' => 'apple');
// this cycle echoes all associative array
// key where value equals "apple"
while ($fruit_name = current($array)) {
if ($fruit_name == 'apple') {
echo key($array).'<br />';
}
next($array);
}
?>
would give you the output,
fruit1
fruit4
fruit5
As simple as that.
current(array_keys($_POST))
should give you what you are looking for. Haven't tested though.
Nice neat way to see the form names that are, or will be submitted
<?php
$i=1;
foreach ($_POST as $name => $value) {
echo "</b><p>".$i." ".$name;
echo " = <b>".$value;
$i++;
}
?>
Just send your form to this script and it will show you what is being submitted.
You can use a foreach Loop to get all values that are set.
foreach ($_POST AS $k=>$v){
echo "$k is $v";
}
Your example
echo $_POST['email'].name; //output: email
wouldnt make sense, since you already know the name of the value you are accessing?

Categories