Here is an example array. The value formatting is HH:MM:SS
$array = ['17:31:05', '17:31:06', '17:31:07' ...etc...];
What I need to do is remove the seconds and the colon before from all values within the $array. My attempt was to do the following, but it did not work.
foreach($array as $key => $val){
$val = substr($val, 0, -3);
}
Any suggestions?
In your questions example code you modify $val and not the $array.
Instead modify the $array:
foreach($array as $key => $val){
$array[$key] = substr($val, 0, -3);
}
or
foreach($array as &$val){
$val = substr($val, 0, -3);
}
unset($val); # remove the reference on $val - recommended child protection
I recommend the first one since reference variables are somewhat error-prone (harder to understand).
Your code is not too far off, you just put it in the wrong manner onto the array. Look the following different example:
$removeSeconds = function($val) {
return substr($val, 0, -3);
}
$arrayWithoutSeconds = array_map($removeSeconds, $array);
The (anonymous) function contains basically your code and then it uses the array_map function to map that function on to the array.
If you prefer to use foreach this is possible as well, however if you want to write into $val in your case, it must be a reference to the value inside the array and this is not always straight forward.
For an array (that is not a reference and not containing any references as "values"), it works as the following:
foreach ($array as &$val) {
### ^-- iterate over a reference (PHP variable alias)
$val = substr($val, 0, -3);
}
unset ($val); ### remove the reference (it does not unset the last array element!)
Even the unset operation after the foreach is technically not necessary, it's recommended so that you can not set $val later on in your code (and then changing the last value of the array).
This is why it is most often more simple to iterate over keys and values, then writing to the specific element directly:
foreach ($array as $key => $val) {
$array[$key] = substr($val, 0, -3);
}
As you can see for all these different cases you could have used the (anonymous) function as on top, therefore using it in the first place would have spared you to change most code. You also have a common mapping situation here, so I think it's most applicable. However this can differ, so keep your mind open and use what you deem fit best in your concrete situation.
You cant use foreach loop for that like this. Use for loop instead
for ($i = 0; $i < count($array); $i++)
{
$array[$i] = substr($array[$i], 0, -3);
}
That's because in a foreach the value of the current element is copied over to the $val variable.
Set $array[$key] with the value you want, and it'll work.
Simple and short solution:
$array = array_map(function($time) {
return substr($time, 0, -3);
}, $array);
This shoud work fine
$result = preg_replace('/(?<=:\d\d):\d+/', '', $array);
or if you need an additional actions inside your loop, do
foreach($array as $key => $val){
$array[$key] = substr($val, 0, -3);
}
Related
I want to remove elements from start of an array, but only certain value. For example, I want to remove all "1" from start of an array.
I want this array:
1,1,2,3,2,3,1,4,5
or this array:
1,1,1,1,2,3,2,3,1,4,5
to became this:
2,3,2,3,1,4,5
Note: There is one more "1", but not repeating on start of an array, I need that to remain in array. Only starting repetitive "1" should be removed.
One PHP line, without for, foreach or other loops, if possible. I know how to do this using loops. I want to know if there is another single line solution for this kind of problem.
Here is a little helper function that will achieve the task:
<?php
function recursively_remove_value_from_start_of_array($value, $arr) {
while(true) {
if( count($arr) > 0 && $arr[0] == $value )
array_shift($arr);
else
break;
}
return $arr;
}
$arr = array(1, 1, 1, 3, 4, 4);
$filtered_array = recursively_remove_value_from_start_of_array(1, $arr);
Here's my try with loops. I don't think there is a one liner solution unless you create a function that does it for you.
foreach($array as $k => $v){
if($v == 1) unset($array[$k]); else break;
}
Hello I'm looking to find the best practice to push an additional field into an Array with php.
I've tried both array_push and its equivalent $array[] = $var; but its not what I'm looking to get.
I have a loop like so:
foreach($lakesNearby as $lakes){
$dist = $this->getDistance($lat, $lng, $lakes['latitude'], $lakes['longitude'], $unit);
$lakes['distance'] = $dist;
$lakesReturned[] = $lakes;
}
But I'm sure there is a better way to combine the two last lines and push it into $lakesNearby ?
Hmmm..., maybe that:
foreach($lakesNearby as &$lakes){
$lakes['distance'] = $this->getDistance($lat, $lng, $lakes['latitude'], $lakes['longitude'], $unit);
}
all data will be in $lakesNearby array, you don't need another array.
As Alex said in the comment:
Just for completeness, see php.net/manual/de/control-structures.foreach.php : "In order to be able to directly modify array elements within the loop precede $value with &. In that case the value will be assigned by reference.
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
$value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>
What is the difference in the following array notations: $arr[$key] = $value and $arr[] = $value, which is a better way ?
function test(){
$key = 0;
$a = array(1,2,3,4,5);
foreach($a as $value){
$a[$key] = $value;
$key++;
}
print_r($a);
}
versus
function test(){
$a = array(1,2,3,4,5);
foreach($a as $value){
$a[] = $value;
}
print_r($a);
}
They are different.
$a[] = 'foo';
Adds an element to the end of the array, creating a new key for it (and increasing the overall size of the array). This is the same as array_push($array, 'foo');
$key = 0;
$a[$key] = 'foo';
Sets the 0 element of the array to foo, it overwrites the value in that location... The overall size of the array stays the same... This is the same as $array = array_slice($array, 0, 1, 'foo'); (but don't use that syntax)...
In your specific case, they are doing 2 different things. The first test function will result in an array array(1,2,3,4,5), whereas the second one will result in array(1,2,3,4,5,1,2,3,4,5). [] always adds new elemements to the end.... [$key] always sets....
$arr[$key] = $value sets a specific key to a specific value.
$arr[] = $value adds a value on to the end of the array.
Neither is "better". They serve completely different roles. This is like comparing writing and drawing. You use a pen for both of them, but which you use depends on the circumstance.
One ($a[$key] = $value) youare specifying the $key where PHP will override that array entry if you use the same key twice.
The other ($a[] = $value) PHP is handling the keys itself and just adding the array entry using the next available key.
The whole thing that you are doing is a bit redundant though, as in the first example you are trying to loop through the array setting its values to itself. In the second example you are duplicating the array.
If you want to append an element to the array I would use
$arr[] = $value;
It is simpler and you get all the information on that line and don't have to know what $key is.
I've created this method to change every value in an array. I'm kinda new to PHP, so I think there should be a more efficient way to do this.
Here's my code:
foreach($my_array as $key => $value)
{
$my_array[$key] = htmlentities($value);
}
Is there a better way to do this?
Thank you in advance.
You'd probably be better off with array_map
$my_array = array_map( 'htmlentities' , $my_array);
You can reference the array and change it
foreach ($array as &$value) {
$value = $value * 2;
}
When you need to apply a function to the value and reassign it to the value, Galen's answer is a good solution. You could also use array_walk(), although it doesn't read as easily as a nice, simple loop.
When you only need to assign, for example, a primitive value to each element in the array, the following will work.
If your keys are numeric, you can use array_fill():
array_fill(0, sizeof($my_array), "test");
If you're using an associative array, you can probably use array_fill_keys(), with something like:
array_fill_keys(array_keys($my_array), "test");
If you mark $value as a reference (&$value) any change you make on $value will effect the corresponding element in $my_array.
foreach($my_array as $key => &$value)
{
$value = "test";
}
e.g.
$my_array = array(1,2,3,4,5,6);
foreach($my_array as &$value)
{
$value *= 5;
}
echo join($my_array, ', ');
prints
5, 10, 15, 20, 25, 30
(And there's also array_map() if you want to keep the original array.)
foreach($my_array as &$value)
{
$value = "test";
}
You could use array_fill, starting at 0 and going to length count($my_array). Not sure if it's better though.
Edit: Rob Hruska's array_fill_keys code is probably better depending on what you define as better (speed, standards, readability etc).
Edit2: Since you've now edited your question, these options are now no longer appropriate as you require the original value to be modified, not changed entirely.
If I had an array like:
$array['foo'] = 400;
$array['bar'] = 'xyz';
And I wanted to get the first item out of that array without knowing the key for it, how would I do that? Is there a function for this?
reset() gives you the first value of the array if you have an element inside the array:
$value = reset($array);
It also gives you FALSE in case the array is empty.
PHP < 7.3
If you don't know enough about the array (you're not sure whether the first key is foo or bar) then the array might well also be, maybe, empty.
So it would be best to check, especially if there is the chance that the returned value might be the boolean FALSE:
$value = empty($arr) ? $default : reset($arr);
The above code uses reset and so has side effects (it resets the internal pointer of the array), so you might prefer using array_slice to quickly access a copy of the first element of the array:
$value = $default;
foreach(array_slice($arr, 0, 1) as $value);
Assuming you want to get both the key and the value separately, you need to add the fourth parameter to array_slice:
foreach(array_slice($arr, 0, 1, true) as $key => $value);
To get the first item as a pair (key => value):
$item = array_slice($arr, 0, 1, true);
Simple modification to get the last item, key and value separately:
foreach(array_slice($arr, -1, 1, true) as $key => $value);
performance
If the array is not really big, you don't actually need array_slice and can rather get a copy of the whole keys array, then get the first item:
$key = count($arr) ? array_keys($arr)[0] : null;
If you have a very big array, though, the call to array_keys will require significant time and memory more than array_slice (both functions walk the array, but the latter terminates as soon as it has gathered the required number of items - which is one).
A notable exception is when you have the first key which points to a very large and convoluted object. In that case array_slice will duplicate that first large object, while array_keys will only grab the keys.
PHP 7.3+
PHP 7.3 onwards implements array_key_first() as well as array_key_last(). These are explicitly provided to access first and last keys efficiently without resetting the array's internal state as a side effect.
So since PHP 7.3 the first value of $array may be accessed with
$array[array_key_first($array)];
You still had better check that the array is not empty though, or you will get an error:
$firstKey = array_key_first($array);
if (null === $firstKey) {
$value = "Array is empty"; // An error should be handled here
} else {
$value = $array[$firstKey];
}
Fake loop that breaks on the first iteration:
$key = $value = NULL;
foreach ($array as $key => $value) {
break;
}
echo "$key = $value\n";
Or use each() (warning: deprecated as of PHP 7.2.0):
reset($array);
list($key, $value) = each($array);
echo "$key = $value\n";
There's a few options. array_shift() will return the first element, but it will also remove the first element from the array.
$first = array_shift($array);
current() will return the value of the array that its internal memory pointer is pointing to, which is the first element by default.
$first = current($array);
If you want to make sure that it is pointing to the first element, you can always use reset().
reset($array);
$first = current($array);
another easy and simple way to do it use array_values
array_values($array)[0]
Just so that we have some other options: reset($arr); good enough if you're not trying to keep the array pointer in place, and with very large arrays it incurs an minimal amount of overhead. That said, there are some problems with it:
$arr = array(1,2);
current($arr); // 1
next($arr); // 2
current($arr); // 2
reset($arr); // 1
current($arr); // 1 !This was 2 before! We've changed the array's pointer.
The way to do this without changing the pointer:
$arr[reset(array_keys($arr))]; // OR
reset(array_values($arr));
The benefit of $arr[reset(array_keys($arr))]; is that it raises an warning if the array is actually empty.
Test if the a variable is an array before getting the first element. When dynamically creating the array if it is set to null you get an error.
For Example:
if(is_array($array))
{
reset($array);
$first = key($array);
}
We can do
$first = reset($array);
Instead of
reset($array);
$first = current($array);
As reset()
returns the first element of the array after reset;
You can make:
$values = array_values($array);
echo $values[0];
Use reset() function to get the first item out of that array without knowing the key for it like this.
$value = array('foo' => 400, 'bar' => 'xyz');
echo reset($value);
output //
400
Starting with PHP 7.3.0 it's possible to do without resetting the internal pointer. You would use array_key_first. If you're sure that your array has values it in then you can just do:
$first = $array[array_key_first($array)];
More likely, you'll want to handle the case where the array is empty:
$first = (empty($array)) ? $default : $array[array_key_first($array)];
You can try this.
To get first value of the array :-
<?php
$large_array = array('foo' => 'bar', 'hello' => 'world');
var_dump(current($large_array));
?>
To get the first key of the array
<?php
$large_array = array('foo' => 'bar', 'hello' => 'world');
$large_array_keys = array_keys($large_array);
var_dump(array_shift($large_array_keys));
?>
In one line:
$array['foo'] = 400;
$array['bar'] = 'xyz';
echo 'First value= ' . $array[array_keys($array)[0]];
Expanded:
$keys = array_keys($array);
$key = $keys[0];
$value = $array[$key];
echo 'First value = ' . $value;
You could use array_values
$firstValue = array_values($array)[0];
You could use array_shift
I do this to get the first and last value. This works with more values too.
$a = array(
'foo' => 400,
'bar' => 'xyz',
);
$first = current($a); //400
$last = end($a); //xyz