str_replace a NULL value - php

I'm trying to use str_replace to replace '' values to 'phone', I've used the code below but it isn't replacing anything:
<?php
$start_up = str_replace('','phone','start_up');
$sales = str_replace('','phone','');
$resourcing = str_replace('','phone','resourcing');
$management = str_replace('','phone','');
$array = "($start_up OR $sales OR $resourcing OR $management)";
echo $array;
?>
I want this to come up with:
(start_up OR phone OR resourcing OR phone)
But instead it is doing this:
(start_up OR OR resourcing OR )
I know I can use a !isset($var) type query but this seems clunky and long winded. Is there a way to include blank strings in a str_replace query?

You can use preg_replace instead of str_replace:
$start_up = preg_replace('/^$/','phone','start_up');
$sales = preg_replace('/^$/', 'phone', '');
$resourcing = preg_replace('/^$/','phone','resourcing');
$management = preg_replace('/^$/','phone','');
$array = "($start_up OR $sales OR $resourcing OR $management)";
echo $array;
Output:
(start_up OR phone OR resourcing OR phone)
and it will replace, an empty string with phone.
Edit: OR you can use empty() and ternary operator:
$start_up = empty('start_up') ? 'phone' : 'start_up';
$sales = empty('') ? 'phone' : '';
$resourcing = empty('resourcing') ?'phone' : 'resourcing';
$management = empty('') ? 'phone' : '';
$array = "($start_up OR $sales OR $resourcing OR $management)";
echo $array;
Output same as above.

Related

How to Insert The Values

I have a variable like:
foreach ($array as $data){
$namee=$data['Label_Field'];
${$namee} = $_POST[$namee];
}
How do I get a value like ("data", "data") using those variables?
you can use $$ in php
Example:
$a = 'name';
$$a = 'test';
echo $name;
Result:
test
Example of your code:
foreach ($array as $data){
$namee = $data['Label_Field'];
$$namee = $_POST[$namee];
}
I also suggest you read the following:
https://www.php.net/manual/en/language.variables.variable.php
https://www.geeksforgeeks.org/php-vs-operator/
https://www.javatpoint.com/php-dollar-doubledollar
what is "$$" in PHP
Avoid using variable variables, simply filter $_POST into a new variable, else there is a likely risk of overwriting important variables ($db_connection?).
Instead do some thing like:
<?php
$_POST['foo'] = '';
$_POST['bar'] = '';
$_POST['baz'] = '';
// fields
$fields = [['Label_Field' => 'foo']];
// just labels
$labels = array_column($fields, 'Label_Field');
// filter $_POST by keys which are in $labels
$data = array_filter($_POST, fn($k) => in_array($k, $labels), ARRAY_FILTER_USE_KEY);
print_r($data);
Then use $data['foo'] instead of $foo.
View online: https://3v4l.org/vna02

Broke string into vars with variable position

I need to broke a string into some vars but its order is not fixed as the exemple:
$string = "name='John';phone='555-5555';city='oakland';";
$string2 = "city='oakland';phone='555-5555';name='John';";
$string3 = "phone='555-5555';name='John';city='oakland';";
so I need to broke the strings into:
$name
$phone
$city
if the position would be fixed i could use explode and call for the array key that i need like
$brokenString = explode("'",$string);
$name = $brokenString[1];
$phone = $brokenString[3];
$city = $brokenString[5];
however how could I do it with variable position??
One way to do it with sort to make the position same always for all string variables.
<?php
$string = "name='John';phone='555-5555';city='oakland';";
$string2 = "city='oakland';phone='555-5555';name='John';";
$string3 = "phone='555-5555';name='John';city='oakland';";
$array = explode(';',$string3);
sort($array);
$array = array_filter($array); # remove the empty element
foreach($array as $value){
$split = explode('=',$value);
$result[$split[0]] = $split[1];
}
extract($result); # extract result as php variables
echo "\$city = $city; \$name = $name; \$phone = $phone";
?>
EDIT: As using extract() is generally not a good idea.You can use simple foreach() instead of extract(),
foreach($result as $k => $v) {
$$k = $v;
}
WORKING DEMO: https://3v4l.org/RB8pT
There might be a simpler method, but what I've done is created an array $stringVariables which holds the exploded strings.
This array is then looped through and strpos is used in each element in the exploded string array to see if it contains 'city', 'phone', or 'name'. Depending on which one, it's added to an array which holds either all the names, cities or phone numbers.
$stringVariables = array();
$phones = array();
$names = array();
$cities = array();
$stringVariables[] = explode(";",$string);
$stringVariables[] = explode(";",$string2);
$stringVariables[] = explode(";",$string3);
foreach($stringVariables as $stringVariable) {
foreach($stringVariable as $partOfString) {
if(strpos($partOfString, "name=") !== false) {
$names[] = $partOfString;
}else if(strpos($partOfString, "city=") !== false) {
$cities[] = $partOfString;
}else if(strpos($partOfString, "phone=") !== false) {
$phones[] = $partOfString;
}
}
}
An alternative way is to convert it into something that can be parsed as a URL string.
First part is to change the values and , from 'John', to John& using a regex ('([^']+)'; which looks for a ' up to a ' followed by a ;), then parse the result (using parse_str())...
$string = "name='John';phone='555-5555';city='oakland';";
$string = preg_replace("/'([^']+)';/","$1&", $string);
echo $string.PHP_EOL;
parse_str( $string, $values );
print_r($values);
gives the output of
name=John&phone=555-5555&city=oakland&
Array
(
[name] => John
[phone] => 555-5555
[city] => oakland
)
or just using regex's...
preg_match_all("/(\w*)?='([^']+)';/", $string, $matches);
print_r(array_combine($matches[1], $matches[2]));

Insert a Variable of String into an array

I'm using a Sendinblue SMTP into my PHP project and I want to send transactionals emails to a dynamic list of emails, the problem is that I have a syntax error when I'm using a variable instead a string. For example, this code works great:
include 'Mailin.php';
$mailin = new Mailin('senders#sender.com', 'key');
$mailin->
addTo(
array(
'email1#email.com' => '', 'email2#email.com' => '', 'email3#email.com' => ''
)
)->
setFrom('sender#sender.com', 'Test')->
setReplyTo('sender#sender.com', 'Test')->
setSubject('Example')->
setText('Test')->
setHtml($htmlContent);
$res = $mailin->send();
print_r($res);
But if I use a variable instead the Strings in "addTo Array" it shows syntax error, for example:
$customers = '';
foreach ($clientes as $customer) {
for ($i=1; $i < 41; $i++) {
if ($customer['email'.$i] != "" or $customer['email'.$i] != NULL) {
$customers .= "'".$customer['email'.$i]. "' => '', " ; //for each customer's email add the email in " 'email#email.com' => '', " format
}
}
}
$customers = substr($customers, 0, -2); //removes last space and comma of the String
include 'Mailin.php';
$mailin = new Mailin('senders#sender.com', 'key');
$mailin->
addTo(
array(
$customers
)
)->
setFrom('sender#sender.com', 'Test')->
setReplyTo('sender#sender.com', 'Test')->
setSubject('Example')->
setText('Test')->
setHtml($htmlContent);
$res = $mailin->send();
print_r($res);
If I use the Print_r($customers) function it shows the exact string that I used in my first example, even if I use the code:
$text = "'email1#email.com' => '', 'email2#email.com' => '', 'email3#email.com' => ''";
if ($customers == $text) {
print_r("Yes");
}else{
print_r("No");
}
The result is "Yes", but when I use the variable in
addTo(
array(
$customers
)
)->
shows an error, but if I use the string directly the email is sent
addTo(
array(
'email1#email.com' => '', 'email2#email.com' => '', 'email3#email.com' => ''
)
)->
And I don't know why it shows error if the $customers variable has the string that is needed.
Do you know how to use the variable with the emails that I need to send?
You don't build an array by concatenating strings with => in them. To create an element in an associative array, just assign to that array index.
$customers = [];
foreach ($customers as $customer) {
for ($i = 1; $i < 41; $i++) {
if (!empty($customer["email" . $i])) {
$customers[$customer["email" . $i]] = "";
}
}
}
include 'Mailin.php';
$mailin = new Mailin('senders#sender.com', 'key');
$mailin->
addTo($customers)->
...
Also, see Why non-equality check of one variable against many values always returns true? for why you should have used && rather than || when you were skipping empty emails (which I've simplified by using !empty()).

arraymap vs foreach loop when creating a comma delimited string

I'm creating a comma delimited string for an SQL query. I would like to know what is better arraymap or a foreach loop. Here are my two examples:
$group_ids = "";
foreach ($group_array as $group_id) {
$group_ids .= $group_id . ",";
}
$group_ids = rtrim($group_ids, ',');
vs
$group_ids = "";
array_map(function ($group_id) use ($group_ids) {
$group_ids .= $group_id . ",";
return;
}, $group_array);
$group_ids = rtrim($group_ids, ',');
Or is there a better way? Or is there literally not much difference?
$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
from
http://php.net/manual/en/function.implode.php
would be more efficient
You can also use implode(',',$array_of_ids). Just make sure you trim your values before using the implode.
$ids = ['foo','bar','boo'];
$ids = array_map('trim',$ids);
$ids_list = implode(',',$ids);
echo $ids_list; # foo,bar,boo

Reverse mysql_fetch_assoc (mysql_set_assoc/mysql_encode_assoc)

Is there function encoding an associative array to use in a mySQL INSERT command?
This way you could do:
$array = mysql_fetch_assoc($result);
$array['key'] = 'updated_value';
mysql_query('INSERT INTO table ' . mysql_encode_assoc($array));
mysql_encode_assoc input:
array(
'name' => 'bob',
'vehicle' => 'car'
)
mysql_encode_assoc output:
'(name, vehicle) VALUES(bob, car)'
There is now:
function mysql_encode_assoc($array) {
$kenc = Array();
$venc = Array();
foreach($array as $k=>$v) {
$kenc[] = "`".mysql_real_escape_string($k)."`";
if( $v === null) $venc[] = "NULL";
else $venc[] = '"'.mysql_real_escape_string($v).'"';
}
$keys = "(".implode(",",$kenc).")";
$vals = "(".implode(",",$venc).")";
return $keys." VALUES ".$vals;
}
There's no built in function that I'm aware of. But you can quite easily make on using array_keys() and array_values().
No built-in function.
$sql = array();
foreach ($anArray as $f=>$v) $sql[] = "`{$f}`" = "'".mysql_real_escape_string($v)."'";
$query = "INSERT INTO table SET ".join(",", $sql);

Categories