How to access array index when using explode() in the same line? - php

Can't wrap my head around this...
Say, we explode the whole thing like so:
$extract = explode('tra-la-la', $big_sourse);
Then we want to get a value at index 1:
$finish = $extract[1];
My question is how to get it in one go, to speak so. Something similar to this:
$finish = explode('tra-la-la', $big_sourse)[1]; // does not work
Something like the following would work like a charm:
$finish = end(explode('tra-la-la', $big_sourse));
// or
$finish = array_shift(explode('tra-la-la', $big_sourse));
But what if the value is sitting somewhere in the middle?

Function Array Dereferencing has been implemented in PHP 5.4. For older version that's a limitation in the PHP parser that was fixed in here, so no way around it for now I'm afraid.

Something like that :
end(array_slice(explode('tra-la-la', $big_sourse), 1, 1));
Though I don't think it's better/clearer/prettier than writing it on two lines.

you can use list:
list($first_element) = explode(',', $source);
[1] would actually be the second element in the array, not sure if you really meant that. if so, just add another variable to the list construct (and omit the first if preferred)
list($first_element, $second_elment) = explode(',', $source);
// or
list(, $second_element) = explode(',', $source);

My suggest - yes, I've figured out something -, would be to use an extra agrument allowed for the function. If it is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string. So, if we want to get, say, a value at index 2 (of course, we're sure that the value we like would be there beforehand), we just do it as follows:
$finish = end(explode('tra-la-la', $big_sourse, 3));
explode will return an array that contains a maximum of three elements, so we 'end' to the last element which the one we looked for, indexed 2 - and we're done!

Related

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

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

php explode - needing second element

more out of interested...
$_GET['unique'] = blahblahblah=this_is_what_im_interested_in
I know I can get the second element like this:
$words = explode('=', $_GET['unique']);
echo $words[1];
Is there a way to get this in a single line? - that would then 'hopefully' allow me to add that to function/object call:
$common->resetPasswordReply(... in here I would put it....);
like
$common->resetPasswordReply(explode('=', $_GET['unique'])[1]);
I'm just interested to see if this is possible.
PHP supports the indexing on functions if they are returning arrays/objects; so the following would work too:
echo explode('=', $_GET['unique'])[1];
EDIT
This is termed as array dereferencing and has been covered in PHP documentations:
As of PHP 5.4 it is possible to array dereference the result of a
function or method call directly. Before it was only possible using a
temporary variable.
As of PHP 5.5 it is possible to array dereference an array literal.
This should do it for you.
substr($str, strpos($str, "=")+1);
Strangely enough you can 'almost' do this with list(), but you can't use it in a function call. I only post it as you say 'more out of interest' :-
$_GET['unique'] = "blahblahblah=this_is_what_im_interested_in";
list(, $second) = explode('=', $_GET['unique']);
var_dump($second);
Output:-
string 'this_is_what_im_interested_in' (length=29)
You can see good examples of how flexible list() is in the first set of examples on the manual page.
I think it is worth pointing out that although your example will work:-
$common->resetPasswordReply(explode('=', $_GET['unique'])[1]);
it does kind of obfuscate your code and it is not obvious what you are passing into the function. Whereas something like the following is much more readable:-
list(, $replyText) = explode('=', $_GET['unique']);
$common->resetPasswordReply($replyText));
Think about coming back to your code in 6 months time and trying to debug it. Make it as self documenting as possible. Also, don't forget that, as you are taking user input here, it will need to be sanitised at some point.

How do I use a variable in an array name in PHP? (variable arrays/variable variable?)

I've looked at other questions/answers but I'm not fully understanding it. Furthermore, I haven't found one asking my exact question.
I have 7 arrays storing the start and end times for a business. My PHP program checks for the current day and matches it with the start end time for that day. So right now I have 7 if statements similar to this:
if (date(l) == 'Sunday') {
$start = $SundayAccountingHours['start'];
$end = $SundayAccountingHours['end'];
}
What I want to do is clean up the code. So maybe I could have something like
$start = ${$today}.AccountingHours['start'];
$end = ${$today}.AccountingHours['end'];
How can I make this work? Using the above example I'm getting this: Parse error: syntax error, unexpected '[' in C:\xampp\htdocs\Dev.php on line 22 where line 22 is $start is defined. I can't take out the stuff in the brackets because THAT'S the information I need to really get to.
If you can't tell, I'm still novice at PHP so any help will be appreciated.
Thanks!
if (date(l) == 'Sunday') {
$start = $SundayAccountingHours['start'];
$end = $SundayAccountingHours['end'];
}
First, put quotes around that 'l'. It's looking for a constant named l, and failing to find that it's treating it like a string. This is very bad practice (and should issue a warning).
Secondly, use a multi-dimensional array. You don't need to try and use the day-of-the-week as part of your variable name. e.g.,
$start = $AccountingHours[$today]['start'];
You might discover variable-variables down the road which allow you do something like what you're trying, but I strongly advise you to steer clear of them. I don't think there's a single practical application for them and they only serve to cause confusion and error (cough).
If you MUST use variable variable names (You should really go for multi-dimensional arrays though), try something like this.
$start = ${$today.'AccountingHours'}['start'];
Array elements can be referenced by variables like so:
$myArray[$myVar]
Arrays can also contain other arrays, like so:
$myArray = array();
$myArray['a'] = array();
$myArray['a']['b'] = 'foo';
print $myArray['a']['b']; // prints 'foo'
So combine the two concepts and you can create a multi-dimensional array referenced by variables:
$accountingHours = array();
$accountingHours['Sunday'] = array('start' => ..., 'end' => ...);
// ...
$start = $accountingHours[$today]['start'];

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?

How To Get The Unique Name Count With PHP?

Let's say I have text file Data.txt with:
26||jim||1990
31||Tanya||1942
19||Bruce||1612
8||Jim||1994
12||Brian||1988
56||Susan||2201
and it keeps going.
It has many different names in column 2.
Please tell me, how do I get the count of unique names, and how many times each name appears in the file using PHP?
I have tried:
$counts = array_count_values($item[1]);
echo $counts;
after exploding ||, but it does not work.
The result should be like:
jim-2,
tanya-1,
and so on.
Thanks for any help...
Read in each line, explode using the delimiter (in this case ||), and add it to an array if it does not already exist. If it does, increment the count.
I won't write the code for you, but here a few pointers:
fread reads in a line
explode will split the line based on a delimiter
use in_array to check if the name has been found before, and to determine whether you need to add the name to the array or just increment the count.
Edit:
Following Jon's advice, you can make it even easier for you.
Read in line-by-line, explode by delimiter and dump all the names into an array (don't worry about checking if it already exists). After you're done, use array_count_values to get every unique name and its frequency.
Here's my take on this:
Use file to read the data file, producing an array where each element corresponds to a line in the input.
Use array_filter with trim as the filter function to remove blank lines from this array. This takes advantage that trim returns a string having removed whitespace from both ends of its argument, leaving the empty string if the argument was all whitespace to begin with. The empty string converts to boolean false -- thus making array_filter disregard lines that are all whitespace.
Use array_map with a callback that involves calling explode to split each array element (line of text) into three parts and returning the second of these. This will produce an array where each element is just a name.
Use array_map again with strtoupper as the callback to convert all names to uppercase so that "jim" and "JIM" will count as the same in the next step.
Finally, use array_count_values to get the count of occurrences for each name.
Code, taking things slowly:
function extract_name($line) {
// The -1 parameter (available as of PHP 5.1.0) makes explode return all elements
// but the last one. We want to do this so that the element we are interested in
// (the second) is actually the last in the returned array, enabling us to pull it
// out with end(). This might seem strange here, but see below.
$parts = explode('||', $line, -1);
return end($parts);
}
$lines = file('data.txt'); // #1
$lines = array_filter($lines, 'trim'); // #2
$names = array_map('extract_name', $lines); // #3
$names = array_map('strtoupper', $names); // #4
$counts = array_count_values($names); // #5
print_r($counts); // to see the results
There is a reason I chose to do this in steps where each steps involves a function call on the result of the previous step -- that it's actually possible to do it in just one line:
$counts = array_count_values(
array_map(function($line){return strtoupper(end(explode('||', $line, -1)));},
array_filter(file('data.txt'), 'trim')));
print_r($counts);
See it in action.
I should mention that this might not be the "best" way to solve the problem in the sense that if your input file is huge (in the ballpark of a few million lines) this approach will consume a lot of memory because it's reading all the input in memory at once. However, it's certainly convenient and unless you know that the input is going to be that large there's no point in making life harder.
Note: Senior-level PHP developers might have noticed that I 'm violating strict standards here by feeding the result of explode to a function that accepts its argument by reference. That's valid criticism, but in my defense I am trying to keep the code as short as possible. In production it would be indeed better to use $a = explode(...); return $a[1]; although there will be no difference as regards the result.
While I do feel that this website's purpose is to answer questions and not do homework assignments, I don't acknowledge the assumption that you are doing your homework, since that fact has not been provided. I personally learned how to program by example. We all learn our own ways, so here is what I would do if I were to attempt to answer your question as accurately as possible, based on the information you have provided.
<?php
$unique_name_count = 0;
$names = array();
$filename = 'Data.txt';
$pointer = fopen($filename,'r');
$contents = fread($pointer,filesize($filename));
fclose($pointer);
$lines = explode("\n",$contents);
foreach($lines as $line)
{
$split_str = explode('|',$line);
if(isset($split_str[2]))
{
$name = strtolower($split_str[2]);
if(!in_array($name,$names))
{
$names[] = $name;
$unique_name_count++;
}
}
}
echo $unique_name_count.' unique name'.(count($unique_name_count) == 1 ? '' : 's').' found in '.$filename."\n";
?>

Categories