Strings and Arrays not working like I thought - php

I'm trying to learn more about strings and arrays. I have this bit of code:
<?php
$states = "OH, VA, GA";
$arrayStates = explode(",", $states);
$exists = "GA";
print_r($arrayStates);
if (in_array($exists, $arrayStates)){
echo "<br/>" . $exists . " " . "exists.";
} else {
echo "<br/>" . $exists . " " . "doesn't exist.";
}
?>
According to my feeble mind, GA should exist in the array. If I put $exists = "OH", that works. But the screen is showing this:
Array ( [0] => OH [1] => VA [2] => GA )
GA doesn't exist.
What am I not understanding here?

The array contains the string " GA" with a space as the first character. That's not equal to `"GA", which goesn't have a space.
You should either use explode(", "), $states) or call trim() on each element of the array:
$arrayStates = array_map('trim', explode(",", $states));

You need to explode with a space after the comma.
$arrayStates = explode(", ", $states);

you're splitting with , but your text has spaces, so after split you have:
Array ( [0] => OH [1] => _VA [2] => _GA )
you can either split by ,_ (replace underscore with space)
or you can trim all values after split, like:
foreach ($arrayStates as $k => $v) $arrayStates[$k] = trim($v);

That is because it is being divided by , so your array contents are :
Array
(
[0] => OH
[1] => VA
[2] => GA
)
you need to do $arrayStates = explode(", ", $states);

In $arrayStates after applying explode(...) you have:
$arrayStates[0] stores "OH"
$arrayStates[1] stores " VA"
$arrayStates[2] stores " GA"
Note at index 2 the array is storing " GA" (note the space) instead of "GA" that is because in the explode function you are using ",". To get your code working as you want you should use in the explode function ", " (note the space)

The explode method splits the string on the comma "," ONLY and does not remove the whitespace. As a result you end up comparing "GA" (your $exists) to " GA" (inside of the array, note the whitespace) =]

Related

I'm doing a preg_split but only obtaining a value on the second value of the array - PHP

Whith this code I'm trying to split a string in the "//" but it only gives me a value on the $splits[1] and on the $splits[0] gives me nothing.
while($row = $result->fetch_assoc()) {
$amigos[] = $row["Id2"]."//".$row["ID"];
}
foreach ($amigos as $i => $value) {
$splits = preg_split("//", $value);
$IDAmizade = $splits[0];
$IDAmigo = $splits[1];
$sql = "SELECT `Nome`,`Agrupamento` FROM `Users` WHERE `ID`='$IDAmigo'";
$result = $conn->query($sql);
$row = $result->fetch_assoc();
echo($row["Nome"] . "+" . $row["Agrupamento"] . "+". $IDAmizade . "/");
}
And yes the $_row["Id2"] is returning a number i've confirm that.
The string that i'm trying to split is like: "1//3"
and after the split it gives me splits[0] is nothing and splits[1] is 3
what am I doing wrong?
The reason the 0 index is empty is because when using preg_split in this part preg_split("//", the first argument is the regex which uses / as a delimiter so you are splitting the string on an empty string.
$pattern = "//";
$string = "1//3";
print_r(preg_split($pattern, $string));
Output
Array
(
[0] =>
[1] => 1
[2] => /
[3] => /
[4] => 3
[5] =>
)
If you want to use preg_split with / as a delimiter and split on // you have to escape the forward slash.
$pattern = "/\/\//";
If you would use another delimiter like ~ the pattern would look like
$pattern = "~//~";
As already pointed out, you could use explode instead
$string = "1//3";
print_r(explode("//", $string));
Output
Array
(
[0] => 1
[1] => 3
)
You need to change your preg_split pattern. What you're doing at the moment will split the string up into its component characters.
So
$splits = preg_split("//", $value);
Should be:
$splits = preg_split("[//]", $value);
See more about preg_split here, and more about regular expressions here.
Alternatively, you could use explode, which splits a string by another string.
$splits = explode("//", $value);
As said in comment, why do you have 2 loops? A single one is enough and you don't need to split a string:
while($row = $result->fetch_assoc()) {
$sql = "SELECT `Nome`,`Agrupamento` FROM `Users` WHERE `ID`='" . $row["ID"] . "'";
$result2 = $conn->query($sql);
$row2 = $result2->fetch_assoc();
echo($row2["Nome"] . "+" . $row2["Agrupamento"] . "+". $row["Id2"] . "/");
}
Moreover you'd better use a JOIN instead of doing a second SELECT in the loop. I can't say more because we don't know the schema of the database and what is the database.

php explode by comma ignore thousands seperator

I am scraping the following kind of strings from an external resource which I can't change:
["one item",0,0,2,0,1,"800.12"],
["another item",1,3,2,5,1,"1,713.59"],
(etc...)
I use the following code to explode the elements into an array.
<?php
$id = 0;
foreach($lines AS $line) {
$id = 0;
// remove brackets and line end comma's
$found_data[] = str_replace(array('],', '[',']', '"'), array('','','',''), $line);
// add data to array
$results[$id] = explode(',', $line);
}
Which works fine for the first line, but as the second line uses a comma for the thousands seperator of the last item, it fails there. So somehow I need to disable the explode to replace stuff between " characters.
If all values would be surrounded by " characters, I could just use something like
explode('","', $line);
However, unfortunately that's not the case here: some values are surrounded by ", some aren't (not always the same values are). So I'm a bit lost in how I should proceed. Anyone who can point me in the right direction?
You can use json_decode here since your input string appears to be a valid json string.
$str = '["another item",1,3,2,5,1,"1,713.59"]'
$arr = json_decode($str);
You can then access individual indices from resulting array or print the whole array using:
print_r($arr);
Output:
Array
(
[0] => another item
[1] => 1
[2] => 3
[3] => 2
[4] => 5
[5] => 1
[6] => 1,713.59
)

Querystring parameter explode str_replace array works for only 1 of the delimiters

I am using a explode and str_replace on the get parameter of the query string URL. My goal is to split the strings by certain characters to get to the value in the string that I want. I am having issues. It should work but doesn't.
Here are two samples of links with the query strings and delimiters I'm using to str_replace.
http://computerhelpwanted.com/jobs/?occupation=analyst&position=data-analyst
as you can see the URL above parameter is position and the value is data-analyst. The delimiter is the dash -.
http://computerhelpwanted.com/jobs/?occupation=analyst&position=business+systems+analyst
and this URL above uses same parameter position and value is business+systems+analyst. The delimiter is the + sign.
The value I am trying to get from the query string is the word analyst. It is the last word after the delimiters.
Here is my code which should do the trick, but doesn't for some reason.
$last_wordPosition = str_replace(array('-', '+')," ", end(explode(" ",$position)));
It works if the delimiter is a + sign, but fails if the delimiter is a - sign.
Anyone know why?
You have things in the wrong order:
$last_wordPosition = end(explode(" ", str_replace(array('-', '+'), " ", $position)));
You probably want to split it up so as to not get the E_STRICT error when not passing an variable to end:
$words = explode(" ", str_replace(array('-', '+'), " ", $position));
echo end($words);
Or something like:
echo preg_replace('/[^+-]+(\+|-)/', '', $position);
As #MarkB suggested you should use parse_url and parse_str since it is more appropriate in your case.
From the documentation of parse_url:
This function parses a URL and returns an associative array containing any of the various components of the URL that are present.
From the documentation of parse_str:
Parses str as if it were the query string passed via a URL and sets variables in the current scope.
So here is what you want to do:
$url1 = 'http://computerhelpwanted.com/jobs/?occupation=analyst&position=data-analyst';
$url2 = 'http://computerhelpwanted.com/jobs/?occupation=analyst&position=business+systems+analyst';
function mySplit($str)
{
if (preg_match('/\-/', $str))
$strSplited = split('-', $str);
else
$strSplited = split(' ', $str);
return $strSplited;
}
parse_str(parse_url($url1)['query'], $output);
print_r($values = mySplit($output['position']));
parse_str(parse_url($url2)['query'], $output);
print_r($values = mySplit($output['position']));
OUTPUT
Array
(
[0] => data
[1] => analyst
)
Array
(
[0] => business
[1] => systems
[2] => analyst
)
You said that you needed the last element of those values. Therefore you could find end and reset useful:
echo end($values);
reset($values);
Answering my own question to show how I ended up doing this. Seems like way more code than what the accepted answer is, but since I was suggested to use parse_url and parse_str but couldn't get it working right, I did it a different way.
function convertUrlQuery($query) {
$queryParts = explode('&', $query);
$params = array();
foreach ($queryParts as $param) {
$item = explode('=', $param);
$params[$item[0]] = $item[1];
}
return $params;
}
$arrayQuery = convertUrlQuery($_SERVER['QUERY_STRING']); // Returns - Array ( [occupation] => designer [position] => webmaster+or+website-designer )
$array_valueOccupation = $arrayQuery['occupation']; // Value of occupation parameter
$array_valuePosition = $arrayQuery['position']; // Value of position parameter
$split_valuePosition = explode(" ", str_replace(array('-', '+', ' or '), " ", $array_valuePosition)); // Splits the value of the position parameter into separate words using delimeters (- + or)
then to access different parts of the array
print_r($arrayQuery); // prints the array
echo $array_valueOccupation; // echos the occupation parameters value
echo $array_valuePosition; // echos the position parameters value
print_r($split_valuePosition); // prints the array of the spitted position parameter
foreach ($split_valuePosition as $value) { // foreach outputs all the values in the split_valuePosition array
echo $value.' ';
}
end($split_valuePosition); // gets the last value in the split_valuePosition array
implode(' ',$split_valuePosition); // puts the split_valuePosition back into a string with only spaces between each word
which outputs the following
arrayQuery = Array
(
[occupation] => analyst
[position] => data-analyst
)
array_valueOccupation = analyst
array_valuePosition = data-analyst
split_valuePosition = Array
(
[0] => data
[1] => analyst
)
foreach split_valuePosition =
- data
- analyst
end split_valuePosition = analyst
implode split_valuePosition = data analyst

Create Array out of a plain text variable?

I am trying to create an array from a plain text variable like so in php:
$arraycontent = "'foo', 'bar', 'hallo', 'world'";
print_r( array($arraycontent) );
But it outputs the entire string as [0]
Array ( [0] => 'foo', 'bar', 'hallo', 'world' )
I would like 'foo' to be [0]
bar to be [1] and so on. Any pointers? Is this even possible?
YIKES, why are these all so long?
Here's a one liner:
explode("', '", trim($arraycontent, "'"));
If your string was like this:
$arraycontent = "foo, bar, hallo, world"
With only the commas separating, then you could use explode, like this:
$myArray = explode(", ", $arraycontent);
This will create an array of strings based on the separator you define, in this case ", ".
If you want to keep the string as is, you can use this:
$myArray = explode("', '", trim($arraycontent, "'"));
This will now use "', '" as the separator, and the trim() function removes the ' from the beginning and end of the string.
If this is PHP you could use:
$foo = "'foo', 'bar', 'hallo', 'world'";
function arrayFromString($string){
$sA = str_split($string); array_shift($sA); array_pop($sA);
return explode("', '", implode('', $sA));
}
print_r(arrayFromString($foo));
eval('$array = array('.$arraycontent.');');
Would be the shortest way.
$array = explode(',', $arraycontent);
$mytrim = function($string) { return trim($string, " '"); };
$array = array_map($mytrim, $array);
A safer and therefore better one. If you have different whitespace characters you would have to edit the $mytrim lambda-function.
Here is a variant that based on the input example would work, but there might be corner cases that is not handled as wanted.
$arraycontent = "'foo', 'bar', 'hallo', 'world'";
$arrayparts = explode(',', $arraycontent); // split to "'foo'", " 'bar'", " 'hallo'", " 'world'"
for each ($arrayparts as $k => $v) $arrayparts[$k] = trim($v, " '"); // remove single qoute and spaces in beggning and end.
print_r( $arrayparts ); // Array ( [0] => 'foo', [1] => 'bar', [2] => 'hallo', [3] => 'world' )
This should give what you want, but also note that for example
$arraycontent = " ' foo ' , ' bar ' ' ' ' ', 'hallo', 'world'";
Would give the same output, so the question then becomes how strict are the $arraycontentinput?
If you have to have input like this, I suggest trimming it and using preg_split().
$arraycontent = "'foo', 'bar', 'hallo', 'world'";
$trimmed = trim($arraycontent, " \t\n\r\0\x0B'\""); // Trim whitespaces and " and '
$result = preg_split("#['\"]\s*,\s*['\"]#", $trimmed); // Split that string with regex!
print_r($result); // Yeah, baby!
EDIT: Also I might add that my solution is significantly faster (and more universal) than the others'.
That universality resides in:
It can recognize both " and ' as correct quotes and
It ignores the extra spaces before, in and after quoted text; not inside of it.
Seems you are having problem while creating an array..
try using
<?php
$arraycontent = array('foo', 'bar', 'hallo', 'world');
print_r( array($arraycontent) );
?>
its output will be:
Array ( [0] => Array ( [0] => foo [1] => bar [2] => hallo [3] => world
) )

php change array format for url

I have a weird project I'm working on. I'm totally new to php so it has been a struggle so far.
I have a form that gives an array and posts it:
...
return($keywords);
}
$keywordlist = explode("\r\n", $keywordlist);
foreach($keywordlist as $keyword){
print_r(mixer(strtolower($keyword)));
}
I get this:
Array ( [0] => one [1] => two [2] => three [3] => four [4] => five [5] => six [6] => ....
But would like it to come out like this instead:
%28one%2Ctwo%2Cthree%2Cfour%2Cfive%2Csix%29
Ultimately hope to be able to attach it to the end of a url like ask.com search:
"http://www.ask.com/web?q=(put my keywords here)"
then navigate there
In theory it would be like I typed "(one,two,three,four,five,six)" into the search bar and pressed enter.
Hopefully that makes some sense.
Something like this:
$commaSeparated = implode(',', $array);
$withParens = '(' + $commaSeparated + ')';
$urlEncoded = urlencode($withParens);
print $urlEncoded;
Use the php implode() function.
So you could do this:
$array = new array ( [0] => one [1] => two [2] => three [3] => four [4] => five [5] => six );
$string = '%28'.implode( '%2C', $array ).'%29';
Now $string will be what you need
This code:
$keywords = array('one', 'two', 'three');
$query = '(' . implode(',', $keywords) . ')';
echo('Search query: ' . $query . PHP_EOL);
$query = rawurlencode($query);
echo('Encoded: ' . $query . PHP_EOL);
Gives this output:
Search query: (one,two,three) Encoded:
%28one%2Ctwo%2Cthree%29
$keywordlist = explode("\r\n", $keywordlist);
array_walk($keywordlist, 'strtolower');
$keywords = '('.implode(",", $keywordList).')';
print_ris what prints your array like this.
http://php.net/manual/en/function.print-r.php
How to solve it depends on a few things. What does mixer()do? And is the keywords always in lowercase? If mixer doens't do much and the keywords are in lowercase you could do something like:
$string = '%28' . implode('%2C',
$keyword) . '%29';
If it's URL encoding you are after you could use the function url_encode instead of manually adding encoded values as above.
Something like this?
$input = array('one', 'two', 'three');
$s = implode(',', $input);
$s = '('.$i.')';
print urlencode($s);
You could encode each part of the array using urlencode and then manually put it in your url (making a url string by yourself). http://php.net/manual/en/function.urlencode.php
Or you could use this function instead: http://php.net/manual/en/function.http-build-query.php

Categories