I am fairly new to PHP and i appear to have reached a roadblock in my code.I have a variable which contains a sequence of numbers separated by a space. I intend on submitting each number into the database as an individual record. My question is how can i deconstruct the variable into individual integers with the intention of submitting each integer as a new record. Here is my code:
foreach ($domains as $domain)
{
$clicked_domains = array($form_entry->{"domain_$domain->id"});
if($clicked_domains){
foreach($clicked_domains as $final_selection){
if ($final_selection != 0){
echo $final_selection." "; // $final_selection now has the value of 17 20 12
}
}
}
}
I would now like to extract each integer from $final_selection (excluding the spaces) for submission to the DB
Check out explode():
Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter.
You can use explode to create an array of integers, and then just loop through each one.
$integer_array = explode(" ", $final_selection);
foreach($integer_array as $integer) {
//submit $integer
}
Related
The following is the code
<?php
$id ="202883-202882-202884-0";
$str = implode('-',array_unique(explode('-', $id)));
echo $str;
?>
The result is
202883-202882-202884-0
for $id ="202883-202882-202882-0";, result is 202883-202882-0
I would like to replace the duplicate value with zero, so that the result should be like 202883-202882-0-0, not just remove it.
and for $id ="202883-0-0-0";, result should be 202883-0-0-0. zero should not be replaced, repeating zeros are allowed.
How can I archive that?
More info:
I want to replace every duplicate numbers. Because this is for a product comparison website. There will be only maximum 4 numbers. each will be either a 6 digit number or single digit zero. all zero means no product was selected. one 6 digit number and 3 zero means, one product selected and 3 blank.
Each 6 digit number will collect data from database, I dont want to allow users to enter same number multiple times (will happen only if the number is add with the URL manually.).
Update: I understand that my question was not clear, may be my English is poor.
Here is more explanation, this function is for a smartphone comparison website.
The URL format is sitename.com/compare.html?id=202883-202882-202889-202888.
All three numbers are different smartphones(their database product ID).
I dont want to let users to type in the same product ID like id=202883-202882-202882-202888. It will not display two 202882 results in the website, but it will cause some small issues. The URL will be same without change, but the internal PHP code should consider it as id=202883-202882-202888-0.
The duplicates should be replaced as zero and added to the end.
There will be only 4 numbers separated by "-".
The following examples might clear the cloud!
if pid=202883-202882-202889-202888 the result should be 202883-202882-202889-202888
if pid=202883-202883-202883-202888 the result should be 202888-0-0-0
if pid=202883-202882-202883-202888 the result should be 202883-202882-202888-0
if pid=202882-202882-202882-202882 the result should be 202882-0-0-0
I want to allow only either 6 digit numbers or single digit zero through the string.
if pid=rgfsdg-fgsdfr4354-202883-0 the result should be 202883-0-0-0
if pid=fasdfasd-asdfads-adsfds-dasfad the result should be 0-0-0-0
if pid=4354-45882-445202882-202882 the result should be 202882-0-0-0
It is too complicated for me create, I know there are bright minds out there who can do it much more efficiently than I can.
You can do a array_unique (preserves key), then fill the gaps with 0. Sort by key and you are done :)
+ on arrays will unify the arrays but prioritizes the one on the left.
Code
$input = "0-1-1-3-1-1-3-5-0";
$array = explode('-', $input);
$result = array_unique($array) + array_fill(0, count($array), 0);
ksort($result);
var_dump(implode('-',$result));
Code (v2 - suggested by mickmackusa) - shorter and easier to understand
Fill an array of the size of the input array. And replace by leftover values from array_unique. No ksort needed. 0s will be replaced at the preserved keys of array_unique.
$input = "0-1-1-3-1-1-3-5-0";
$array = explode('-', $input);
$result = array_replace(array_fill(0, count($array), 0), array_unique($array));
var_export($result);
Working example.
Output
string(17) "0-1-0-3-0-0-0-5-0"
Working example.
references
ksort - sort by key
array_fill - generate an array filled with 0 of a certain length
This is another way to do it.
$id = "202883-202882-202882-0-234567-2-2-45435";
From the String you explode the string into an array based on the delimiter which in this case is '-'/
$id_array = explode('-', $id);
Then we can loop through the array and for every unique entry we find, we can store it in another array. Thus we are building an array as we search through the array.
$id_array_temp = [];
// Loop through the array
foreach ($id_array as $value) {
if ( in_array($value, $id_array_temp)) {
// If the entry exists, replace it with a 0
$id_array_temp[] = 0;
} else {
// If the entry does not exist, save the value so we can inspect it on the next loop.
$id_array_temp[] = $value;
}
}
At the end of this operation we will have an array of unique values with any duplicates replaced with a 0.
To recreate the string, we can use implode...
$str = implode('-', $id_array_temp);
echo $str;
Refactoring this, using a ternary to replace the If,else...
$id_array = explode('-', $id);
$id_array_temp = [];
foreach ($id_array as $value) {
$id_array_temp[] = in_array($value, $id_array_temp) ? 0 : $value;
}
$str = implode('-', $id_array_temp);
echo $str;
Output is
202883-202882-0-0-234567-2-0-45435
This appears to be a classic XY Problem.
The essential actions only need to be:
Separate the substrings in the hyphen delimited string.
Validate that the characters in each substring are in the correct format AND are unique to the set.
Only take meaningful action on qualifying value.
You see, there is no benefit to replacing/sanitizing anything when you only really need to validate the input data. Adding zeros to your input just creates more work later.
In short, you should use a direct approach similar to this flow:
if (!empty($_GET['id'])) {
$ids = array_unique(explode('-', $_GET['id']));
foreach ($ids as $id) {
if (ctype_digit($id) && strlen($id) === 6) {
// or: if (preg_match('~^\d{6}$~', $id)) {
takeYourNecessaryAction($id);
}
}
}
At the moment my "method" checks if the array_key is in the array, i need to add that if the key length is 13 it is okay, but when it is longer it has to delete the like first 5 numbers of the list. My code searches the price according to my key out of the database, and compares it to a list where the "keys" are a bit different. So to make it easier to understand:
The key in my database is: 2840529503100
The key in the table where i have to get the price from is: 000002840529503100
So what i basically need to do is get a substring from the "list" or "table" which takes the last 13 numbers because the right keys of my database are always 13 numbers long.
$teile = array();
while ($dbRow = $sqlres->fetch_assoc()) {
$teile[$dbRow['nummer']] = $dbRow;
if (array_key_exists($fileRow[0], $teile)) {
If your first five 0 values is constant means you can use substr() like this:
$str = '000002840529503100';
echo $str2 = substr($str, 5);
Another method for substr() is only keep the last last 13 digits like this:
$str = '000002840529503100';
echo $str2 = substr($str, -13);
Else to remove the first 0 values you can use ltrim() like this:
echo ltrim('000002840529503100', '0');
Note: without quotes these two functions won't work.
As an alternative to Nawins solution you can also use PHP Typecasting to automatically remove the leading zeros.
NOTE: for my example; I can't see which variable you're trying to change. But assumed the first...
Thus:
$fileRow[0] = "000002840529503100"
(int)$fileRow[0] = "2840529503100";
This would make:
if (array_key_exists((int)$fileRow[0], $teile)) {
...
}
BEWARE:
This example doesn't change the stored value of $fileRow[0] so using it as a future key reference (~print $array[$fileRow[0]]) will still use the longer number until the (int) version has been set as the variable/key value, example:
$fileRow[0] = (int)$fileRow[0];
I have a list of numbers then I want to put comma on each number works fine, but the problem if number exceed to 14 my output become scientific format
Like this 1,.,1,1,1,1,1,1,1,1,1,E,+,2,8
but i want to be like this 1,1,1,1,1,1,1,1,0,0,0,0,1,1,1,
here's sample code below
<?php
$val = 11111111110000000000000000111;
$val = (string)$val; // convert into a string
$arr = str_split($val, "1"); // break string in 3 character sets
$val_new = implode(",", $arr); // implode array with comma
echo $val_new;
?>
Thanks
This is because it exceeds the max value of an integer. There is nothing much you can do about it.
Input that exceeds this limit will always be converted to a floating point representation. This means the input should immediatly be formatted as a string:
$val = "11111111110000000000000000111";
$arr = str_split($val, 1); // break string in 3 character sets
$val_new = implode(",", $arr); // implode array with comma
echo $val_new;
This happens because the number is too large, so php automatically converts it into the scientific format. you can avoid this by defining the number as string initially (by putting it inside quotations)...try changing your code to this:
$val = "11111111110000000000000000111";
and remove this line:
$val = (string)$val; // convert into a string
let me know how it went.
The variable $page includes a webpage (full HTML file), but I want to filter that file on this line:
<a href="http://[website]/[folder]/
And I want that the 5 characters after parsed in a string.
But that strings is multiple times inside $page, so the numbers has to be stored in an array too.
So if a match is found with <a href="http://[website]/[folder]/23455, how do I get the '23455' into $nums[0]
And if another match is found with <a href="http://[website]/[folder]/12345, the '12345' will be put into $nums[1]
Take a look at http://net.tutsplus.com/tutorials/other/8-regular-expressions-you-should-know/ maybe this regular expression works for you:
/^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/
From what I understand from your question you are just trying to get the ending piece of the url and then do a comparison then store the value in an array? I believe this code should do the trick.
$nums = new array(); //declare your array
$a = new SimpleXMLElement('Your Link'); //create a new simple xml element
$a = $a['href'];
$array = explode("/",$a); //split the string into an array by using the / as the delimiter
if($array[count($array)-1] == '23455') { //get the count of the array and -1 from the count to get the last index then compare to required number
$nums[0] = '23455'; //store value in array
} else if ($array[count($array)-1] == '12345'{
$nums[1] = '12345'; //
}
What i am trying to do is really but i am going into a lot of detail to make sure it is easily understandable.
I have a array that has a few strings in it. I then have another that has few other short strings in it usually one or two words.
I need it so that if my app finds one of the string words in the second array, in one of the first arrays string it will proceed to the next action.
So for example if one of the strings in the first array is "This is PHP Code" and then one of the strings in the second is "PHP" Then it finds a match it proceeds to the next action. I can do this using this code:
for ( $i = 0; $i < count($Array); $i++) {
$Arrays = strpos($Array[$i],$SecondArray[$i]);
if ($Arrays === false) {
echo 'Not Found Array String';
}
else {
echo 'Found Array String';
However this only compares the First Array object at the current index in the loop with the Second Array objects current index in the loop.
I need it to compare all the values in the array, so that it searches every value in the first array for the First Value in the second array, then every value in the First array for the Second value in the second array and so on.
I think i have to do two loops? I tried this but had problems with the array only returning the first value.
If anyone could help it would be appreciated!
Ill mark the correct answer and + 1 any helpful comments!
Thanks!
Maybe the following is a solution:
// loop through array1
foreach($array1 as $line) {
// check if the word is found
$word_found = false;
// explode on every word
$words = explode(" ", $line);
// loop through every word
foreach($words as $word) {
if(in_array($word, $array2)) {
$word_found = true;
break;
}
}
// if the word is found do something
if($word_found) {
echo "There is a match found.";
} else {
echo "No match found."
}
}
Should give you the result you want. I'm absolute sure there is a more efficient way to do this.. but thats for you 2 find out i quess.. good luck
You can first normalize your data and then use PHP's build in array functions to get the intersection between two arrays.
First of all convert each array with those multiple string with multiple words in there into an array only containing all words.
A helpful function to get all words from a string can be str_word_count.
Then compare those two "all words" arrays with each other using array_intersect.
Something like this:
$words1 = array_unique(str_word_count(implode(' ', $Array), 1));
$words2 = array_unique(str_word_count(implode(' ', $SecondArray), 1));
$intersection = array_intersect($words1, $words2);
if(count($intersection))
{
# there is a match!
}
function findUnit($packaging_units, $packaging)
{
foreach ($packaging_units as $packaging_unit) {
if (str_contains(strtoupper($packaging[3]), $packaging_unit)) {
return $packaging_unit;
}
}
}
Here First parameter is array and second one is variable to find