refactoring and using a counter? - php

I have the following structure:
$text_1 = $this->getValue('value_1');
$text_2 = $this->getValue('value_2');
$text_3 = $this->getValue('value_3')
And also the following:
foreach($text_1 as $t_1)
{
if(!$first)
{
$string_1 .= ",";
}
$first = false;
$string_1 .= $t_1;
}
foreach($text_2 as $t_2)
{
if(!$first)
{
$string_2 .= ",";
}
$first = false;
$string_2 .= $t_2;
}
foreach($text_3 as $t_3)
{
if(!$first)
{
$string_3 .= ",";
}
$first = false;
$string_3 .= $t_3;
}
I was wondering if this could be re-factored to use a counter, like in a for loop, to replace the _1, _2, _3 etc from my code?

Well, the foreach-loops can be replaced with implode.
Other than that, wouldn't it be better to use an array for your $text_?? variables? Eg.:
$text = $this->getValue('value');
foreach ($text as $value) {
$strings[] = implode(",", $value);
}
Hard to give more concrete advise, without the exact context, but that should get you in the right direction.

I hope this one helps u...
$arrOutput = compact('text_1', 'text_2', 'text_3');
foreach($arrOutput as $t1)
{
$out1[] = implode(",", $t1);
}
print_r($out1);

Yes, you should probably be using an array or map to hold the values and iterating over that, assuming that the values you're dealing with are all the same sort of thing.

Ok so I figured out a way of doing it:
for ($i=1;$i<=12;$i++) {
$choices = $this->getValue('question_'.$i);
$serialized = "";
$first = true;
foreach($choices as $choice)
{
if(!$first)
{
$serialized .= ",";
}
$first = false;
$serialized .= $choice;
}
$this->setValue('question_'.$i, $serialized);
}
This seems to work well!

Related

Need to change case of a string - PHP

$variable = "test_company_insurance_llc_chennai_limited_w-8tyu.pdf";
I need to display above the $variable like
Test Company Insurance LLC Chennai Limited W-8TYU.pdf
For that I've done:
$variable = str_replace("_"," ","test_company_insurance_llc_chennai_limited_w-8tyu.pdf");
$test = explode(" ", $variable);
$countof = count($test);
for ($x=0; $x<$countof; $x++) {
if($test[$x] == 'w-8tyu' || $test[$x] == 'llc') {
$test[$x] = strtoupper($test[$x]);
//todo
}
}
I've got stuck in the to-do part.
I will change the specific words to uppercase using strtoupper.
Later, how should I need to merge the array?
Any help will be thankful...
$str_in = "test_company_insurance_llc_chennai_limited_w-8tyu.pdf";
$lst_in = explode("_", $str_in);
$lst_out = array();
foreach ($lst_in as $val) {
switch($val) {
case "llc" : $lst_out[] = strtoupper($val);
break;
case "w-8tyu.pdf" : $lst_temp = explode('.', $val);
$lst_out[] = strtoupper($lst_temp[0]) . "." . $lst_temp[1];
break;
default : $lst_out[] = ucfirst($val);
}
}
$str_out = implode(' ', $lst_out);
echo $str_out;
Not terribly elegant, but perhaps slightly more flexible.
$v = str_replace("_"," ","test_company_insurance_llc_chennai_limited_w-8tyu.pdf");
$acronyms = array('llc', 'w-8tyu');
$ignores = array('pdf');
$v = preg_replace_callback('/(?:[^\._\s]+)/', function ($match) use ($acronyms, $ignores) {
if (in_array($match[0], $ignores)) {
return $match[0];
}
return in_array($match[0], $acronyms) ? strtoupper($match[0]) : ucfirst($match[0]);
}, $v);
echo $v;
The ignores can be removed provided you separate the extension from the initial value.
See the code below. I have printed the output of the code as your expected one. So Run it and reply me...
$variable = str_replace("_"," ","test_company_insurance_llc_chennai_limited_w-8tyu.pdf");
$test = explode(" ", $variable);
$countof = count($test);
for ($x=0; $x<$countof; $x++) {
if($test[$x] == 'llc') {
$test[$x] = strtoupper($test[$x]);
//todo
}elseif($test[$x] == 'w-8tyu.pdf'){
$file=basename($test[$x],'pdf');
$info = new SplFileInfo($test[$x]);
$test[$x] = strtoupper($file).$info->getExtension();
}
else{
$test[$x]=ucfirst($test[$x]);
}
}
echo '<pre>';
print_r($test);
echo '</pre>';
echo $output = implode(" ", $test);

Simplify and Abstract my Code: Combining Strings

I want to combine strings in PHP. My script creates every possible combination like below.
$part1 = array('','d','n','s','g');
$part2 = array('a','e','o','oo');
$part3 = array('m','n','s','d','l','t','g','j','p');
$part4 = array('g','p','l','');
$part5 = array('g','p','l');
$part6 = array('a','e','o');
$part7 = array('d','l','r','');
$names = array();
foreach ($part1 as $letter1) {
foreach ($part2 as $letter2) {
foreach ($part3 as $letter3) {
foreach ($part4 as $letter4) {
foreach ($part5 as $letter5) {
foreach ($part6 as $letter6) {
foreach ($part7 as $letter7) {
$names[] = $letter1 . $letter2 . $letter3 . $letter4 . $letter5 . $letter6 . $letter7;
}
}
}
}
}
}
}
But I am not happy with my solution. I is quick and dirty code. Is there a solution wich works with a flexible number of part arrays, so I can extend the script by e.g. $part8 easiely? (without changing the loop construction)
Recursive one:
function buildNames( $parts, $chars = ''){
// Nothing to do, shouldn't happen
if( !count( $parts)){
return array();
}
$names = array();
$part = array_shift( $parts);
// Max level, we can build final names from characters
if( !count( $parts)){
foreach( $part as $char){
$names[] = $chars . $char;
}
return $names;
}
// "We need to go deeper" and build one more level with remembered chars so far
foreach( $part as $char){
$names = array_merge( $names, buildNames( $parts, $chars . $char));
}
return $names;
}
$parts = array( $part1, $part2, $part3, $part4, $part5, $part6, $part7);
$names = buildNames( $parts);
From head, from scratch, comment if something, but idea should be good
You could reduce this problem to six cartesian products:
cartesianProduct($part1,
cartesianProduct($part2,
cartesianProduct($part3,
cartesianProduct($part4,
cartesianProduct($part5,
cartesianProduct($part6, $part7))))));
function cartesianProduct($p1, $p2) {
$ret = array();
foreach($p1 as $l1)
foreach($p2 as $l2)
$ret[] = $l1 . $l2;
return $ret;
}

Accessing PHP associative array with index represented as string

Is it possible to do something like this in PHP?
$index1 = "[0][1][2]";
$index2 = "['cat']['cow']['dog']";
// I want this to be $myArray[0][1][2]
$myArray{$index1} = 'stuff';
// I want this to be $myArray['cat']['cow']['dog']
$myArray{$index2} = 'morestuff';
I've searched for a solution, but I don't think I know the keywords involved in figuring this out.
eval('$myArray[0][1][2] = "stuff";');
eval('$myArray'.$index1.' = "stuff";');
But be careful when using eval and user input as it is vulnerable to code injection attacks.
Not directly. $myArray[$index] would evaluate to $myArray['[0][1][2]']. You would probably have to separate each dimension or write a little function to interpret the string:
function strIndexArray($arr, $indices, $offset = 0) {
$lb = strpos($indices, '[', $offset);
if ($lb === -1) {
return $arr[$indices];
}
else {
$rb = strpos($indices,']', $lb);
$index = substr($indices, $lb, $rb - $lb);
return strIndexArray($arr[$index], substr($indices, $rb+1));
}
}
You can probably find some regular expression to more easily extract the indices which would lead to something like:
$indices = /*regex*/;
$value = '';
foreach($indices as $index) {
$value = $array[$index];
}
To set a value in the array the following function could be used:
function setValue(&$arr, $indices, $value) {
$lb = strpos($indices, '[');
if ($lb === -1) {
$arr = $value;
}
else {
$rb = strpos($indices, ']', $lb);
$index = substr($indices, $lb, $rb);
setValue($arr[$index], substr($indices, $lb, $rb+1), $value);
}
}
Note: I made above code in the answer editor so it may contain a typo or two ; )
$index1 = "[0][1][2]";
$index2 = "['cat']['cow']['dog']";
function myArrayFunc(&$myArray,$myIndex,$myData) {
$myIndex = explode('][',trim($myIndex,'[]'));
$m = &$myArray;
foreach($myIndex as $myNode) {
$myNode = trim($myNode,"'");
$m[$myNode] = NULL;
$m = &$m[$myNode];
}
$m = $myData;
}
// I want this to be $myArray[0][1][2]
myArrayFunc($myArray,$index1,'stuff');
// I want this to be $myArray['cat']['cow']['dog']
myArrayFunc($myArray,$index2,'morestuff');
var_dump($myArray);
There's always the evil eval:
eval('$myArray' . $index1 . ' = "stuff";');
You can use two anonymous functions for this.
$getThatValue = function($array){ return $array[0][1][2]; };
$setThatValue = function(&$array, $val){ $array[0][1][2] = $val; };
$setThatValue($myArray, 'whatever');
$myValue = $getThatValue($myArray);

Check if key exists in $_SESSION by building index string

I need to check if a key exists and return its value if it does.
Key can be an array with subkeys or endkey with a value.
$_SESSION['mainKey']['testkey'] = 'value';
var_dump(doesKeyExist('testkey'));
function doesKeyExist($where) {
$parts = explode('/',$where);
$str = '';
for($i = 0,$len = count($parts);$i<$len;$i++) {
$str .= '[\''. $parts[$i] .'\']';
}
$keycheck = '$_SESSION[\'mainKey\']' . $str;
if (isset(${$keycheck})) {
return ${$keycheck};
}
// isset($keycheck) = true, as its non-empty. actual content is not checked
// isset(${$keycheck}) = false, but should be true. ${$var} forces a evaluate content
// isset($_SESSION['mainKey']['testkey']) = true
}
Using PHP 5.3.3.
Instead of building the string, just check if the key exists within your loop.
For instance:
function doesKeyExist($where) {
$parts = explode('/',$where);
$currentPart = $_SESSION['mainKey'];
foreach($parts as $part) {
if (!isset($currentPart[$part])) {
return false;
}
$currentPart = $currentPart[$part];
}
return true;
}
function getByKeys($keys, $array) {
$value = $array;
foreach (explode('/', $keys) as $key) {
if (isset($value[$key])) {
$value = $value[$key];
} else {
return null;
}
}
return $value;
}
Perhaps I'm misunderstanding the question, but this would appear to be the simplest way of doing it:
function getKey($arr, $key) {
if (array_key_exists($key, $arr)) {
return $arr[$key];
} else {
return false;
}
}
$value = getKey($_SESSION['mainKey'], 'testkey');
You should use $$keycheck, not ${$keycheck}.
The last notation is only if you use the variable inside a string (e.g. "${$keycheck}")
See http://php.net/manual/en/language.variables.variable.php for more details about variable variables
You might want to use the eval() php function for this.
function doesKeyExist($where) {
$parts = explode('/',$where);
$str = '';
for($i = 0,$len = count($parts);$i<$len;$i++) {
$str .= '["'. $parts[$i] .'"]';
}
eval('$keycheck = $_SESSION["mainKey"]' . $str . ';');
if (isset($keycheck)) {
return $keycheck;
}
}
HTH

How do I combine all elements in an array using comma?

I know this question has with out any doubt been asked a whole lot of times. I though can seem to find a solution. So forgive me if it's way to simple.
The question is how do access the end of a while loop.
E.g.
while($countByMonth = mysql_fetch_array($countByMonthSet)) {
$c = $countByMonth["COUNT(id)"];
echo $c . "," ;
}
How do I manage separate each value of the while loop by a comma but of course I don't want the comma at the end of the value.
In advance thank you very much for your help :)
You can:
1) Build a string, and remove the last character:
$c = '';
while ($countByMonth = mysql_fetch_array($countByMonthSet)) {
$c .= $countByMonth["COUNT(id)"] . ',';
}
$c = substr($c, 0, -1);
echo $c;
2) Build an array and use implode()
$c = array();
while ($countByMonth = mysql_fetch_array($countByMonthSet)) {
$c[] = $countByMonth["COUNT(id)"];
}
echo implode(',', $c);
Tip: You can use aliases in your query, like: SELECT COUNT(id) as count FROM .... Then you can access it as $countByMonth['count'], which looks cleaner IMO.
The simple1 solution:
$isFirst = true;
while($countByMonth = mysql_fetch_array($countByMonthSet)) {
$c = $countByMonth["COUNT(id)"];
if ($isFirst) {
$isFirst = false;
} else {
echo = ', ';
}
echo $c;
}
Alternatively, you could implode() the values. Or - perhaps easier to read/understand/maintain - concatenate it all into a string and remove the last "," (SO eats my whitespace; the string is comma-whitespace):
$list = '';
while($countByMonth = mysql_fetch_array($countByMonthSet)) {
$c = $countByMonth["COUNT(id)"];
$list .= $c . ', ';
}
echo substring($list, 0, -2); // Remove last ', '
(Several other answers propose the use of an accumulated array and then use implode(). From a performance perspective this method will be superior to string concatenation.)
1 See comments.
Alternatively you can do:
$arr = array();
while($countByMonth = mysql_fetch_array($countByMonthSet)) {
$arr[] = $countByMonth["COUNT(id)"];
}
echo implode(', ',$arr);
Or afterwards just trim it off with rtrim($c, ',')
While I think the implode solution is probably best, in situations where you can't use implode, think of the basic algorithm differently. Rather than "how can I add a comma behind every element but the last?" ask yourself "how can I add a comma before every element but the first?"
$str = '';
$count = count( $array );
if( $count ) {
$i = 0;
$str = $array[$i];
$i++;
while( i < $count ) {
$str .= ','.$array[$i];
$i++;
}
}
If you "shift" the first element, then you can use a foreach loop:
$str = '';
if( count( $array ) ) {
$str = array_shift( $array );
foreach( $array as $element ) {
$str .= ', '.$element;
}
}
Ty this:
int count;//
while(i)
{
count=i;
}

Categories