Insert a Variable of String into an array - php

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()).

Related

Getting extra slashes while using JSON array in PHP

I am getting some extra slashes while making json array using PHP. My code is below.
<?php
$output=array(array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA001","subject"=>"Mathematics"),array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA002","subject"=>"History"),array("first_name"=>"Rama","last_name"=>"Nayidu","reg_no"=>13,"paper_code"=>"BA001","subject"=>"Geology"),array("first_name"=>"robin","last_name"=>"sahoo","reg_no"=>12,"paper_code"=>"BA003","subject"=>"Science"));
$result = []; // Initialize result array
foreach ($output as $key => $value) {
$name = $value['first_name'] . ' ' . $value['last_name'];
// check if same name already has entry, create one if not
if (!array_key_exists($name, $result)) {
$result[$name] = array(
'reg_no' => $value['reg_no'],
'name' => $name,
'paper1' => '',
'paper2' => '',
'paper3' => '',
'paper4' => ''
);
}
// count array elements with value, then set paper number and value
$paper = 'paper' . (count(array_filter($result[$name])) - 1);
$result[$name][$paper] = $value['paper_code'].'/'.$value['subject'];
}
$result = array_values($result); // reindex result array
echo json_encode($result);exit;
?>
Here the json output is given below.
[{"reg_no":12,"name":"robin sahoo","paper1":"BA001\/Mathematics","paper2":"BA002\/History","paper3":"BA003\/Science","paper4":""},{"reg_no":13,"name":"Rama Nayidu","paper1":"BA001\/Geology","paper2":"","paper3":"","paper4":""}]
Here my problem is I am adding $value['paper_code'].'/'.$value['subject']; and in output I am getting "BA001\/Mathematics". Here One extra slash(\) is added which I need to remove.
You can add JSON_UNESCAPED_SLASHES as the second parameter. LIke:
$result = array_values($result); // reindex result array
echo json_encode($result,JSON_UNESCAPED_SLASHES);exit;
This will result to:
[{"reg_no":12,"name":"robin sahoo","paper1":"BA001/Mathematics","paper2":"BA002/History","paper3":"BA003/Science","paper4":""},{"reg_no":13,"name":"Rama Nayidu","paper1":"BA001/Geology","paper2":"","paper3":"","paper4":""}]
Doc: json_encode()

parse css with media queries and other end cases to php array

id like to break a css file to php array.
i have this code:
function parseCss($css_str) {
$css = array();
// TODO include external css
$css_str = preg_replace('/(#import\s+["\'].+["\'];)/', "", $css_str);
// Strip all line endings and both single and multiline comments
$css_str = preg_replace('/\s*(?!<\")\/\*+[^\*]+\*+\/(?!\")\s*/', "", $css_str);
$css_class = explode("}", $css_str);
while(list($key, $value) = each($css_class)){
$aCSSObj = explode("{", $value);
$cssSelector = strtolower(trim($aCSSObj[0]));
if($cssSelector){
// regular class not in media query
$cssprops[] = $cssSelector;
$a = explode(";", $aCSSObj[1]);
while(list($key, $val0) = each($a)){
if(trim($val0)){
$aCSSSub = explode(":", $val0);
$cAtt = strtolower(trim($aCSSSub[0]));
if(isset($aCSSSub[1])){
$aCSSItem[$cAtt] = trim($aCSSSub[1]);
}
}
}
if((isset($css[$cssSelector])) && ($css[$cssSelector])){
$aCSSItem = array_merge($css[$cssSelector], $aCSSItem);
}
$css[$cssSelector] = (isset($aCSSItem)) ? $aCSSItem : null ;
unset($aCSSItem);
}
if(strstr($cssSelector, ",") && !strstr($cssSelector, "#media")){
$aTags = explode(",", $cssSelector);
print_r($aTags);
foreach($aTags as $key0 => $value0){
$css[$value0] = $css[$cssSelector];
}
unset($css[$cssSelector]);
}
}
unset($css_str, $css_class, $aCSSSub, $aCSSItem, $aCSSObj);
return $css;
}
but that doesn't return me a css file with media queries like it supposed to be.
and if there is a ":" sign in the css value -for example an IE expression like that:
top:expression((-20+(document.documentElement.clientHeight ?document.documentElement.clientHeight/2:document.body.clientHeight/2)+(ignoreMe = document.documentElement.scrollTop ? document.documentElement.scrollTop:document.body.scrollTop))+'px')
its giving back cutted code.
so the result should look like that:
Array
(
[selector] => array (
[prop] => value
[prop2] => value
)
[#media handheld,only screen and (max-width:320px)] => array(
[selector] => array(
[prop] => value
[prop2] => value
)
)
)
how do i make it work?
Solved that!
eventually I've used CSSTidy to parse the css, and it does the job beautifully!
http://csstidy.sourceforge.net/index.php

PHP serialization error with ' " counts as two characters

I'm having problems with php serialization, when ever ' " are included i get an extra character space. Ex if it's 6 characters i get 7
$episodes_count = sizeof($episode_title);
$episodes = array();
$content = '';
for ($i = 0; $i <= $episodes_count; $i++) {
$title = htmlspecialchars($episode_title[$i], ENT_QUOTES);
$airdate = $episodes_airdates[$i];
$season = $episodes_seasons[$i];
$number = $episodes_numbers[$i];
$plot = $episodes_plot[$i];
// check if empty
if (!empty($title) && !empty($number ) && !empty($plot )) {
$episodes[] = array(
'title' => $title,
'airdate' => $airdate,
'season' => $season,
'number' => $number,
'plot' => $plot,
);
}
}
// Serialized Episodes in case they exist, if not, remove the goal post
if ( sizeof($episodes) > 0 ) {
$content = str_replace("'", '%',serialize($episodes));
}
update_post_meta($post_id, 'episodes', $content);
}
You pass some data that looks serialized to wordpress to update_post_meta - wordpress can have a problem with that and the data will get broken while stored and retrieved.
To prevent that, you can prefix the string so that it does not look serialized any longer or you even encode the whole string, e.g. with base64_encode. That will prevent wordpress and other components to modify the values due to encoding issues.

php - create assciative array while loop

I am trying to create 2 new arrays out of one existing array ($array), using the following "foreach" loop. However I am not sure it is correct:
$emails = array();
$numbers = array();
while($array){
$entry = $array['entry1'];
$number = number($entry);
if(isset($number) && (strlen($number) > 9)){
$numbers[] = array('entry1' => $entry, 'number' => $number);
}
else{
$email = email($entry);
$emails[] = array('entry1' => $entry, 'email' => $email);
}
}
should the internal arrays have []?
do I even need to start the arrays outside of the while loop? or skip it?
is it better to use a foreach loop?
Update:
Okay, here is the original array: It is extracted from a mysql query, of sets of two numbers:
{('uid1','uid2'),('uid1','uid5'),('uid9','uid93'),....)
There might be other data in each row, but these are the only two data points that really matter.
What I am trying to do is for a specific user ($entry), create two separate arrays: of all the users that have numbers (that's a function we have), and all the rest - of their emails.
So the outcome will be 2 new arrays which will look like this:
for a specific uid79887:
numbers array: {('uid8','xxx-xxxx-xxx'),('uid34','yyy-yyyy-yyy'),('uid654','vvv-vvvv-vvv')}
emails array: {('uid4','mmm#mmm.com'),('uid1','lll#lll.com'),('uid55554','ppp#ppp.com')}
Few things first:
It's good practice to initialize your variables, just do it (it has many positives).
What kind of test is while($array)? You should use foreach( $array as $entry) or while( count( $array)) if you're removing items from array.
Why are you testing isset( $number) when it's always set? It's initialized variable. You're probably checking null, so use !is_null() or ($number !== null). Even if it works it's misleading.
I guess your code should look like this:
$emails = array();
$numbers = array();
foreach( $array as $entry){
$entry = isset( $entry['entry1']) ? $entry['entry1'] : null;
$number = number( $entry);
if( strlen($number) > 9 ){ // If $number is empty it will have strlen < 1 .)
$numbers[] = array('entry1' => $entry, 'number' => $number);
} else {
$emails[] = array('entry1' => $entry, 'email' => email( $entry));
}
}
I guess this is what you are trying to acheive:
$emails = $numbers = Array();
foreach($array as $item) {
$e = $item['entry1'];
$number = number($e);
if(strlen($number) > 9) {
$numbers[] = Array('entry1' => $e, 'number' => $number);
}
else {
$email = email($entry);
$emails[] = Array('entry1' => $e, 'email' => $email);
}
}
in your code, while($array) do not loop on the array, it loop until $array == false
as $array do not change in your loop it will either never enter or the loop, or never exit
generally, using a foreach loop produce code easier to understand
Assuming this isn't some kind of homework assignment, why don't you do it this way:
$emails = array();
$numbers = array();
foreach( $array as $entry )
{
$number = number($entry);
if( $number && strlen($number) > 9 )
{
array_push($numbers, array('entry1' => $entry, 'number' => $number));
}
else
{
array_push($emails, array('entry1' => $entry, 'email' => email($entry)));
}
}
It is better to use built in functions that trying to roll your own. The foreach() function works very well.

PHP array key is NULL, array appears empty

I'm rather new to PHP and I am kind of stuck here writing this simple script; what I am trying to ultimately do is go through the content of a string and find the positions of all the occurrences I have listed in my $definitions array then map those positions in a separate array and return it...
rather simple but I am not sure where the problem arises, when i print_r on the array in different parts of code, thinking its a scope issue, I keep seeing that the key value of the array is NULL and also when I try and access a value of the array I am sure exists for a given key, i also get nothing; any help would be appreciated...
thank you!
<?php
class html2DokuWiki {
function definition_map($content){
$definitions = array("<title" => " ","<h" => array("=", 6),"<p" => "\n\n","<b" => "**","<strong" => "**","<em" => "//","<u" => "__","<img" => " ","<a" => " ","<ul" => " ","<ol" => "*","<li" => "-","<dl" => " ","<dt" => " ","<dd" => " ");
$element_pos = array();
foreach($definitions as $html_element){
$offset = 0;
$counter = 0;
$element_pos[(string)$html_element] = array(); //ask phil why do i need to cast in order to use the object?
while($offset = strpos($content, $html_element, $offset + 1)){
$element_pos[(string)$html_element][] = $offset;
};
};
//print_r($element_pos);
echo $element_pos["<p"][0];
return $element_pos;}
function run($page){
return $this->definition_map($page);}
};
$debug = new html2DokuWiki();
$url = "http://www.unixwiz.net/techtips/sql-injection.html";
$content = file_get_contents($url);
//echo $content;
//print_r($debug->run($content));
$test = $debug->run($content);
echo "<p> THIS:".$test["<p"][0]."</p>";
//print_r($test);
?>
If it's the key you want to use as $html_element as an index you should do:
foreach($definitions as $html_element => $value){

Categories