Reset PHP array index to start from 0 after unset operation [duplicate] - php

This question already has answers here:
How to re-index the values of an array in PHP? [duplicate]
(3 answers)
Closed 2 years ago.
I have an array
$cars = array("Volvo", "BMW", "Toyota", "Mercedes");
I wanted to remove first element "Volvo" and i use this
unset($cars[0]);
Now i have an array like this:
Array
(
[1] Bmw
[2] Toyota
[3] Mercedes
)
But i want to my array begins again with zero, to be like this:
Array
(
[0] Bmw
[1] Toyota
[2] Mercedes
)
How to do it?

Use array_values function to reset the array, after unset operation.
Note that, this method will work for all the cases, which include unsetting any index key from the array (beginning / middle / end).
array_values() returns all the values from the array and indexes the array numerically.
Try (Rextester DEMO):
$cars = array("Volvo", "BMW", "Toyota", "Mercedes");
unset($cars[0]);
$cars = array_values($cars);
var_dump($cars); // check and display the array

Use array_slice() instead that select special part of array
$newCars = array_slice($cars, 1)
Check result in demo

Assuming you always want to remove the first element from the array, the array_shift function returns the first element and also reindexes the rest of the array.
$cars = array("Volvo", "BMW", "Toyota", "Mercedes");
$first_car = array_shift($cars);
var_dump($first_car);
// string(5) "Volvo"
var_dump($cars)
// array(3) {
// [0] =>
// string(3) "BMW"
// [1] =>
// string(6) "Toyota"
// [2] =>
// string(8) "Mercedes"
//}

Related

How to save only numeric numbers from string into an array of int in PHP

in my POST variable i have: print_r($_POST["partecipanti"]);
It displays
["1", "2"]
I want to save only the numbers of the post variable in an int array. I tried
$array = array();
preg_match_all('/-?\d+(?:\.\d+)?+/', $_POST["partecipanti"], $array);
But print_r($array) returns
Array (
[0] => Array (
[0] => 1
[1] => 2
)
)
How can i have a variable like
Array (
[0] => 1
[1] => 2
)
Hope i explained good, thanks all in advance
preg_match_all returns a new multidimensional array every time. But you could just "pop" the array:
$array = array();
preg_match_all('/-?\d+(?:\.\d+)?+/', $_POST["partecipanti"], $array);
$array = $array[0];
Returns:
Array (
[0] => 1
[1] => 2
)
to filter integer values from an array, use array_filter
$arr = array_filter($_POST["participanti"], function($v) { return is_int($v); });
In case you want to convert the array values into integers:
$arr = array_map(function($v) { return (int)$v; }, $_POST["participanti"]);
In both cases the $arr contains only integer values.
Assuming $_POST["partecipanti"]) is a string because you use it directly in your example and the second parameter of preg_match_all is a string.
preg_match_all returns an array where the matches are in the first entry and contains array of strings. You could get that array by using $array[0] .
Besides 1 and 2, your regex -?\d+(?:\.\d+)?+ also matches for example -8.44 or 99999999999999999999999999.
If you want an array of int, you could use array_map with for example the function intval for the callback.
Note the maximum size of an int and the rounding of the values.
For example:
$str = "test 1, test 2, test 2.3 and -8.44 plus 99999999999999999999999999999999999999999999999999";
preg_match_all('/-?\d+(?:\.\d+)?/', $str, $array);
$array = array_map/**/("intval", $array[0]);
var_dump($array);
Demo
That results in:
array(5) {
[0]=>
int(1)
[1]=>
int(2)
[2]=>
int(2)
[3]=>
int(-8)
[4]=>
int(9223372036854775807)
}

change array value in php through array place [duplicate]

This question already has answers here:
Deleting an element from an array in PHP
(25 answers)
Closed 5 years ago.
How to change or update array value in PHP through array number?
Example:
$array1 = array("cat","dog","mouse","dog");
I want to change the value of dog in the 2nd array only
Use Variable variables:
$a = 'array' . '1';
$$a[1] = 'doggg'; #value changed
$b = 'array' . '2';
$$b[1] = 'newDogg'; #value changed
if you want to remove 2 index then
$array1 = array('dog','mouse','cat','mouse');
unset($array1[1]);
print_r($array1);
Output
Array ( [0] => dog [2] => cat [3] => mouse )
//if you are looking for remvoing duplicate value then you can use array_unique
$result=array_unique($array1);
print_r($result);
Output
Array ( [0] => dog [1] => mouse [2] => cat )
If you mean you have to remove an element from an array, probably this will help.
array_splice( $array1, OFFSET, 1 );
replace OFFSET with the index you want to remove.
Edit :-
To delete element use unset(arrayVar[key])
For eg :-
unset($array1[1]) - will delete the "mouse" at key/index 1 if you wish to delete 2nd occurance then use unset($array1[3])
Original :-
Explain your problem in more detail please !
What do you mean by 2nd array and where exactly is it ?
Do you mean to edit the 2nd occurance of "dog" in array ?
If so then it would be $array1[3]="someNewValue"

Convert a multidimensional array into simpler form [duplicate]

This question already has answers here:
Turning multidimensional array into one-dimensional array [duplicate]
(11 answers)
Closed 7 years ago.
I have an array as shown below,
How to convert the above array1 into array2 form?
array1
Array
(
[0] => Array
(
[0] => 500 GB
)
[1] => Array
(
[0] => 100 GB
)
)
array2
Array
(
[0] => 500 GB
[1] => 100 GB
)
$yourArray = [[0 => '500 GB'], [0 => '100 GB'], [1 => '200 GB']];
$result = array_filter(
array_map(
function($element) {
if (isset($element[0])) {
return $element[0];
}
return;
},
$yourArray
),
function($element) {
return $element !== null;
}
);
echo var_dump($result); // array(2) { [0]=> string(6) "500 GB" [1]=> string(6) "100 GB" }
This will work only with php >= 5.4 (because of array short syntax). If you're running on older versione, just substitute [] with array()
Explaination
array_filter is used to exclude certain values from an array (by using a callback function). In this case, NULL values that you get from array_map.
array_map is used to apply a function to "transform" your array. In particular it applies a function to each array element and returns that element after function application.

How to combine an array with another array

I've two arrays array1 and array2 and I want to add all elements of array2 to the end of array1. array1 contains many items.
The keys are numeric and I don't want this syntax:
array1 = array1 + array2
or
array1 = SomeArrayFun(array1,array2)
As it takes away CPU times ( as array is created twice )
What I want is:
array1 . SomeAddFun(array2); // This will not create any new arrays
Is there any way to do it?
If you'd like to append data to an existing array you should se array_splice.
With the proper arguments you'll be able to insert/append the contents of $array2 into $array1, as in the below example.
$array1 = array (1,2,3);
$array2 = array (4,5,6);
array_splice ($array1, count ($array1), 0, $array2);
print_r ($array1);
output:
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
You might use ArrayObject with the append function:
$arrayobj = new ArrayObject(array('first','second','third'));
$arrayobj->append('fourth');
Result:
object(ArrayObject)#1 (5) {
[0]=>
string(5) "first"
[1]=>
string(6) "second"
[2]=>
string(5) "third"
[3]=>
string(6) "fourth"
}
Don't know for appending arrays though, as they seem to be appended as a "subarray" and not as part of the whole.
Docs: http://www.php.net/manual/en/arrayobject.append.php

php reassign array contents [duplicate]

This question already has answers here:
Transposing multidimensional arrays in PHP
(12 answers)
Closed 1 year ago.
any particular function or code to put this kind of array data
ori [0] => 43.45,33,0,35 [1] => 74,10,0,22 [2] => 0,15,0,45 [3] => 0,0,0,340 [4] => 12,5,0,0 [5] => 0,0,0,0
to
new [0] => 43.45,74,0,0,12,0 [1] => 33,10,15,0,5,0 [2] => 0,0,0,0,0,0, [3] => 35,22,45,340,0,0
As you can see, the first value from each ori are inserted into the new(0), the second value from ori are inserted into new(1) and so on
If $ori is an array of arrays, this should work:
function transpose($array) {
array_unshift($array, null);
return call_user_func_array('array_map', $array);
}
$newArray = transpose($ori);
Note: from Transposing multidimensional arrays in PHP
If $ori is not an array of arrays, then you'll need to convert it first (or use the example by Peter Ajtai), like this:
// Note: PHP 5.3+ only
$ori = array_map(function($el) { return explode(",", $el); }, $ori);
If you are using an older version of PHP, you should probably just use the other method!
You essentially want to transpose - basically "turn" - an array. Your array elements are strings and not sub arrays, but those strings can be turned into sub arrays with explode() before transposing. Then after transposing, we can turn the sub arrays back into strings with implode() to preserve the formatting you want.
Basically we want to go through each of your five strings of comma separated numbers one by one. We take each string of numbers and turn it into an array. To transpose we have to take each of the numbers from a string one by one and add the number to a new array. So the heart of the code is the inner foreach(). Note how each number goes into a new sub array, since $i is increased by one between each number: $new[$i++][] =$op;
foreach($ori as $one) {
$parts=explode(',',$one);
$i = 0;
foreach($parts as $op) {
$new[$i++][] =$op;
}
}
$i = 0;
foreach($new as $one) {
$new[$i++] = implode(',',$one);
}
// print_r for $new is:
Array
(
[0] => 43.45,74,0,0,12,0
[1] => 33,10,15,0,5,0
[2] => 0,0,0,0,0,0
[3] => 35,22,45,340,0,0
)
Working example

Categories