PHP: Removing elements from array - php

My question is about the PHP functions for manipulating array elements, like array_pop() and array_shift().
On all examples I've seen (including php.net), since those functions return the value being removed, they are assigned to a variable when executed, for example:
$exampleArray=array("1","2","3");
$removedNum=array_pop($exampleArray);
What I can't find is whether you have to assign the removed value or could you just pop the value from the end and be done with it, like in Ruby, for example.
I have tried and it works, e.g.:
array_pop($exampleArray);
but I'm not sure if this is an acceptable practice in PHP programming? Or should I always assign the value to a variable?

It is valid to use array_pop() and array_shift() to remove unwanted values, and in some cases, can even make sense depending on the data that you're working with.
I.e., if you are working with CSV files, and have an array of lines from that file, where the first line is header data that you know will never change (a bold assumption), and that does not matter to your script, you can safely remove that first line from your array before starting the loop to process the values.
As for whether that's a good practice or not, that's something to discuss with the people maintaining your code...

You can just:
array_pop($exampleArray);
You don't have to assign the value to a variable if you don't need to use it.

It depends on what your application is doing. For example if your application really needs to save the last number being popped then yes. Otherwise, you don't need the variable. Furthermore, It takes memory to create a variable. It may not seem as much for small operations but if you have a loop of a billion operations, then this becomes wasteful. As long as you code is readable, you'll be fine :).

Related

How much is the limitation of argument length in a function in PHP?

How much is the limitation of argument length is passed to a function in PHP?
Is this possible to send output of a mysql query with more than 2000 records as an array to a function to render the result as a grid?
In theory there are no limitations on parameter size in PHP I can think of. And even if there are any you can probably just increase their limit in the php.ini
However here's an idea on how to make your code more efficient:
In PHP it is possible to pass arguments by reference rather than by value. This means your function only gets told where to find the array instead of copying the whole thing over just to pass it into a function. Implications of that are, that if you modify the array from inside the function those changes will also get visible on the outside since you're working on the same exact array. (Think of it as a share.)

Extracting specific data from a large amount of data in a single "cell" of a mysql database

Long time reader first time questioner...
I'm attempting to use Drupal to create a set of variables, not the issue, it's all in place to set them and simple for the future operator to edit.
I then need to grab these values in php, still on the site but outside of Drupal to some extent. Again, although I'm a bit of a lightweight on PHP, I can get what I need. However drupal stores the data all in one "cell" (apologies, I've searched for what I'm after but I think my vocabulary is lacking to get the right result!). Here's an example of how it is stored:
a:3:{i:0;a:3:{s:5:"value";s:2:"38";s:5:"label";s:11:"Cost Per
M2";s:6:"weight";s:1:"0";}i:1;a:3:{s:5:"value";s:1:"7";s:5:"label";s:13:"Arch
Top
Cost";s:6:"weight";s:1:"1";}i:2;a:3:{s:5:"value";s:1:"5";s:5:"label";s:13:"Flat
Top Cost";s:6:"weight";s:1:"2";}}
So I can happily return the whole contents as above, but I haven't the slightest how to refine it down to a specific reference. I can work out the data is contained between certain sets of brackets so, one ref is:
{s:5:"value";s:2:"38";s:5:"label";s:11:"Cost Per M2";s:6:"weight";s:1:"0";}
What I really need is the "38" in the example, as this is a cost that a 2nd system uses a number of to calculate a final cost.
I hope this makes sense?
The value is serialised (see http://php.net/manual/en/function.serialize.php). What you want to do is unserialize it (see http://www.php.net/manual/en/function.unserialize.php). So it would be:
$deserializedValues = unserialize($values).
After that you can call the variables by doing:
$deserializedValues['value'] (if an array)
$deserializedValues->value (if an object)
Drupal returns JSON. The cleanest way to handle this would be to use PHP's json_decode() function:
http://php.net/manual/en/function.json-decode.php

Compare the size of dynamic output of a function to a destination file, and do a rewrite

I have a function to write a text file based on the form settings, a rather large form.
Shortly, I want to compare the output of a function to a single file, and only do execution (rewriting the file) if the destination file is different from the output. As you guess, it is a performance concern.
Is it doable, BTW?
The process is, I fill up some forms:
A single file is written to contain some "specific" selected options
Some "non-specific" options do not necessarily write anything to the file.
The form is updateable anytime, so the content of the file may grow or shrink based on different options.
It only needs a rewrite to the file if I am at point #1.
When at point #2, nothing should be written.
This is what I tried:
if ($output != file_get_contents($filepath)) {
// save the data
}
But I felt so much delay of execution in this.
I found a almost similar issue here: Can I use file_get_contents() to compare two files?, but my issue is different. Mine is comparing the result of the process to an already existing file which simply the result of the process previously. And only rewrite the file if they are different.
No sensitive data on the form, btw.
Any hint is very much appreciated.
Thanks
To compare a whole file with a string (I suppose it's a string, isn't it?) the only way is to read whole file and do comparison. To improve performance you can read file line by line and stop at first different line, as Explosion Pills said before me.
If your file is really big, and you want to improve performance further, you can do some hashing stuff:
Generate the output, let's say $output.
Calculate md5($output) and store in $output_md5.
Compare $output_md5 with a stored one, let's say in file output.md5.
Are they equal?
If yes, do nothing.
If not, save $output into output.txt and $output_md5 in output.md5.
Rather than load the entire file into memory, it may be faster to read it line-by-line (fgets) and compare it to the input string also line-by-line. You could even go as small as character-by-character, but I think that's overkill.
You could always try a combination of what was in the other post, the sha1_file($file) function, with the sha1($string) function, and check the equality of that.

How can PHP string indexed arrays be achieved efficiently in C++

I’ve been playing around with searching text in big lists and found that using a PHP array seems to be a quick way of doing it.
E.g. if you had loads of place names and associated postcodes you could read them into a PHP array like this:
$place[‘place name here’] = “postcode”;
Then to look up you just take the place you want to look up and plug it in to the array:
$postcode_sought = $place[‘place I want to look up’];
I thought I could speed this up using C++ but of course C++ does not allow (as far as I know) arrays with a string as the index.
The only way I can think to do it is to create vectors for the place and postcode and loop through the place vector looking for a match but the repeated string comparisons take forever as I'd expected. I also experimented with hashing the text but I still couldn’t get it anywhere near as fast as PHP.
I think PHP is written in C so my question is how does C manage to create this string index name functionality for PHP?
I’m not looking for the actual code or anything, it just seems to me that there must be some fundamental technique that is used for this and I was just wondering if there is anyone out there who could briefly explain it.
Thanks in advance.
C
I thought I could speed this up using C++ but of course C++ does not allow (as far as I know) arrays with a string as the index.
It does, You can use std::map as an Associative array.
You could try using Berkeley DB. Back in the days it was the fastest but by default it's disk oriented. I don't know if you can run it in memory but you can always mount the directory from tmpfs.
PHP propably uses some external class for hashing table. You can get quite far by writing a quicksearch algorithm. Sort the keys and check up the key in the middle. Then again in middle until you've found the key. You can also use MD5() for keys as it's faster than pure string comparison.
C and C++ only allow integer types to be array indexes, and strings aren't even a type on C/C++, they're actually an array of chars.
As stated above, use std::map or similar.

Help on understanding JS

I have thos piece of code:
Math&&Math.random?Math.floor(Math.random()*10000000000000):Date.getTime();
And as far as i know && is logic operator for AND, so im trying to convert this into PHP and this is where i got:
intval(floor(time()/10800000)%10+(rand()?floor(rand()*10000000000000):time()))
The problem is that i can't understand the first part
Math&&
Can anyone help with this one cause i always get negative result, when i should get positive (probably the logic rand-time is not working in my php example)
That's a test to make sure the Math class is available in the browser. You don't need that in PHP. The second clause checks to make sure the Math.random method is available. It uses it if it is, and uses the time if it is not.
In PHP, just use rand(). http://us2.php.net/rand
It may just be the ternary operator that is throwing you off.
http://en.wikipedia.org/wiki/Ternary_operation
It's a test to see if the Math variable is non-null/undefined. I've never seen it before, but I assume it's to prevent an error if, for some reason, Math is null (although, I can't imagine why that would happen).
There, your Javascript code is :
Testing if the Math object exists
and has a random method
If yes, using it to generate a random value
else, using the date as fallback to get a random value
In you PHP code, you know that rand() and mt_rand() exist ; no need to test if they do ;-)
Which means the tests and condition are useless, and that you don't need to re-code them in PHP : just keep the part between the ? and the : in the original code.

Categories