Stringing together variables, str_replace. Tidier way to do this? - php

I have a bunch of variables that I want to string together. They all need to be tidied up by removing spaces and commas, and converting to dashes (I'm constructing a URL).
I have a very basic understanding of PHP, but I feel my code below could be tidier and more efficient. Could you point me to some resources or make some suggestions please?
Here's what I have:
$propNum = $prop->Address->Number;
$propStreet = $prop->Address->Street;
$propTown = $prop->Address->Town;
$propPost = $prop->Address->Postcode;
$propFullAdd = array($propNum, $propStreet, $propTown, $propPost);
$propFullAddImp = implode(" ",$propFullAdd);
$propFullAddTidy = str_replace(str_split(' ,'),'-', strtolower($propFullAddImp));
echo $propFullAddTidy;

From the output of your existing code, it seems like you may want an output that looks something like:
12345-example-street-address-example-town-example-postcode
In this case, you could use this solution:
//loop through all the values of $prop->Address
foreach($prop->Address as $value) {
//for each value, replace commas & space with dash
//store altered value in new array `$final_prop`
$final_prop[] = str_replace([' ', ','], '-', $value);
/*
Removing `str_split(' ,')` and subbing an array makes the loop "cheaper" to do,
Because the loop doesn't have to call the `str_split()` function on every iteration.
*/
}
//implode `$final_prop` array to dash separated string
//also lowercase entire string at once (cheaper than doing it in the loop)
$final_prop = strtolower(implode('-', $final_prop));
echo $final_prop;
if you remove the comments, this solution is only 4 lines (instead of 7), and is completely dynamic. This means if you add more values to $prop->Address, you don't have to change anything in this code.
A different method
I feel like this would usually be handled by using http_build_query(), which converts an array into a proper URL-encoded query string. This means that each value in the array would be passed as it's own variable in the URL query.
First, $propFullAdd is not necessary (in fact, it may be detrimental), $prop->Address already contains the exact same array. Recreating the array like this completely removes the ability to tell which value goes to which key, which could be problematic.
This means that you can simplify your entire code by replacing it with this:
echo http_build_query($prop->Address);
Which outputs something like this:
Number=12345&Street=Example+Street+Address&Town=Example+Town&Postcode=Example+Postcode

Related

I need to change the php code in the file so instead of the current json output

So i am using this PHP code to create the json output, and I am having an issue where it’s creating an array of array with the info. I would like to get rid of one array and just display the list of API’s thats been used and number that has been used.
Looks as though the difference is you have...
"apis":[{"item_search":"0\n"},{"item_recommended":"0\n"}]
and want
"apis":{"item_search":"0\n","item_recommended":"0\n"}
If this is the case, you need to change the way you build the data from just adding new objects each time to setting the key values directly in the array...
$zone_1 = [];
foreach($zone_1_apis as $api_name ) {
$zone_1[substr($api_name, 0,-5)] = file_get_contents('keys/'.$_GET['key'].'/zone_1/'.$api_name);
}
You also need to do the same for $zone_2 as well.
It may also be good to use trim() round some of the values as they also seem to contain \n characters, so perhaps...
trim(file_get_contents('keys/'.$_GET['key'].'/zone_1/'.$api_name))

keep adding up code from database

# Check arrary not empty
if (!empty($results)) {
$this->code($results);
// got the mail code from database
// which is PG-000001
// how do i add , like something PG-000001 ++
}
this will return a result from database , my intention is to keep adding up the code that return from my database and the update back to the database.
now it was return PG-000001, how do i make it add up and be like PG-000002 and then update it and next time it will be PG-000002 and up to 000003 and so on.
how do i add up the text PG-000001?
If all of your codes look like this, then your really shouldn’t store them that way. It appears that the PG- at the beginning is just a prefix. If you store the actual value as an integer, you can increment as much as you like.
Anyway, the solution to your question is that you will need to
split the string
increment the second part
zero-pad the second part
combine again
Here is a little test script:
$test='PG-000001';
$pattern='/(.*-)(\d+)/';
preg_match($pattern,$test,$matches);
list(,$prefix,$value)=$matches;
$value=sprintf('%06d',$value+1);
$test="$prefix$value";
print $test;
Translation:
/(.*-)(\d+)/ is the pattern that will split the string into the prefix & numeral
preg_match applies the pattern and returns the result into the array $matches.
$matches has the original string, and then the two matches
list() copies elements of the array into variables. The leading comma skips the first element
sprintf formats the data. In this case, the code 0-pads to 6 digits
the double-quoted string is a simple way of recombining your data.

Elegant way to force two array elements when splitting a string

Assume the following string:
$string = 'entry1_entry2';
What I want to do is something like this:
list($entry1, $entry2) = explode('_', $string);
My question now is are there any elegant ways to force the explode (or any other function) to get 2 array items minimum? You could specify a third parameter to get a maximum of 2 elements but I want a minimum. If there would be a string like this:
$string = 'entry1';
The second line would give a NOTICE because there is only one array element. The best would be a way without checking the resulting array or the string for the presence of the seperator.
You could probably use array_pad:
list($entry1, $entry2) = array_pad(explode('_', $string), 2, NULL);
See array_pad
I'd suggest that storing the explode inside multiple variables is just bad practice, when you can't enforce the integrity of your data.
Should you not simply be using
$entries = explode($string);
and avoid all the unnecessary complications?

APACHE mod_rewrite change variable name in query string

I'm trying to change a variable name in a query string, so it's usable by my PHP code.
The query gets posts from an external system, so I can't control that they are posting a variable name with a space in it. And that makes it impossible for me to use the PHP $_GET function.
I need to change variable%20name to ?new1
And I need to change variable2 to new2
There are many variables passed in the query, but only these two need to be changed. The rest can stay the same or even disappear.
So ?variable%20name=abc&variable2=xyz
Needs to end up as ?new1=abc&new2=xyz
Also, they may not be in this order and there may be more variables
So ?variable%20name=abc&blah=123&blah2=456&variable2=xyz
Could end up as ?new1=abc&new2=xyz
OR as ?new1=abc&blah=123&blah2=456&new2=xyz
Either way would be fine!
Please give me the mod_rewrite rule that will fix this.
Thank you in advance!
Parsing the query string with mod_rewrite is a bit of a pain, has to be done with RewriteCond and using %n replacements in a subsequent RewriteRule, probably easier to manually break up the original query string in PHP.
The full query string can be found (within PHP) in $_SERVER['QUERY_STRING'].
You can split it up using preg_split() or explode(), first on &, then on =, to get key/value pairs.
Using custom%20cbid=123&blahblahblah&name=example as an example.
$params = array();
foreach (explode("&", $_SERVER['QUERY_STRING']) as $cKeyValue) {
list ($cKey, $cValue) = explode('=', $cKeyValue, 2);
$params[urldecode($cKey)] = urldecode($cValue);
}
// Would result in:
$params = array('custom cbid' => 123,
'blahblahblah' => NULL,
'name' => example);

remove duplicate from string in PHP

I am looking for the fastest way to remove duplicate values in a string separated by commas.
So my string looks like this;
$str = 'one,two,one,five,seven,bag,tea';
I can do it be exploding the string to values and then compare, but I think it will be slow. what about preg_replace() will it be faster? Any one did it using this function?
The shortest code would be:
$str = implode(',',array_unique(explode(',', $str)));
If it is the fastest... I don't know, it is probably faster then looping explicitly.
Reference: implode, array_unique, explode
Dealing with: $string = 'one,two,one,five,seven,bag,tea';
If you are generating the string at any point "up script", then you should be eliminating duplicates as they occur.
Let's say you are using concatenation to generate your string like:
$string='';
foreach($data as $value){
$string.=(strlen($string)?',':'').some_func($value);
}
...then you would need to extract unique values from $string based on the delimiter (comma), then re-implode with the delimiter.
I suggest that you design a more direct method and deny duplicates inside of the initial foreach loop, like this:
foreach($data as $value){
$return_value=some_func($value); // cache the returned value so you don't call the function twice
$array[$return_value]=$return_value; // store the return value in a temporary array using the function's return value as both the key and value in the array.
}
$string=implode(',',$array); // clean: no duplicates, no trailing commas
This works because duplicate values are never permitted to exist. All subsequent occurrences will be used to overwrite the earlier occurrence. This function-less filter works because arrays may not have two identical keys in the same array(level).
Alternatively, you can avoid "overwriting" array data in the loop, by calling if(!isset($array[$return_value])){$array[$return_value]=$return_value;} but the difference means calling the isset() function on every iteration. The advantage of using these associative key assignments is that the process avoids using in_array() which is slower than isset().
All that said, if you are extracting a column of data from a 2-dimensional array like:
$string='';
foreach($data as $value){
$string.=(strlen($string)?',':'').$value['word'];
}
Then you could leverage the magic of array_column() without a loop like this:
echo implode(',',array_column($str,'word','word'));
And finally, for those interested in micro-optimization, I'll note that the single call of array_unique() is actually slower than a few two-function methods. Read here for more details.
The bottomline is, there are many ways to perform this task. explode->unique->implode may be the most concise method in some cases if you aren't generating the delimited string, but it is not likely to be the most direct or fastest method. Choose for yourself what is best for your task.

Categories