I get data from this code.
foreach ($datas as $data){
echo $data['product_number']."<br>";
}
Then it will show the data like :
MP/9998/00012
00089
12009
290989
But I want to change my data become
12
120
89
12009
290989
I edit the question. Here's my question before:
I have this array
$data = ["00012", "00120", "00089", "12009", "290989"].
This array have contain at least 5 character. How can I get that array data become
[12, 120, 89, 12009, 290989]
Thank You.
simple use array_map and intval
$data= array('00012','00120','00089','12009','290989');
$new = array_map('intval',$data); //intval function applied to each element in the array
print_r($new);
Update 1: Apply intval
foreach ($datas as $data){
echo intval($data['product_number'])."<br>";
}
Update 2: use filter_var
$str = 'MP/000090';
$int = filter_var($str, FILTER_SANITIZE_NUMBER_INT);
echo intval($int);
Try this:
<?php
$data = array("00012", "00120", "00089", "12009", "290989" );
foreach( $data as $v )
{
echo ltrim($v, "0") . "\n";
}
Live Demo
Output
12
120
89
12009
290989
This will always return your last string of numbers (omitting any preceding zeros) in each element:
Code: (Demo)
$data=array('00012','00120','00089','12009','290989','MP/000090','MP/9998/0023028');
$data=array_map(function($v){return preg_match('~0*\K\d+$~',$v,$out)?$out:'fail';},$data);
var_export($data);
Output:
array (
0 =>
array (
0 => '12',
),
1 =>
array (
0 => '120',
),
2 =>
array (
0 => '89',
),
3 =>
array (
0 => '12009',
),
4 =>
array (
0 => '290989',
),
5 =>
array (
0 => '90',
),
6 =>
array (
0 => '23028',
),
)
Related
I want to capture the first element of an array and its value in a second array, removing it from the first.
Is there a core PHP function that does what my_function does here?
function my_function(&$array) {
$key = current(array_keys($array));
$value = $array[$key];
unset($array[$key]);
return [$key => $value];
}
$array = [
'color' => 'red',
'car' => 'ford'
'house' => 'cottage',
];
$top = my_function($array);
print_r($top);
print_r($array);
Output:
Array
(
[color] => red
)
Array
(
[car] => ford
[house] => cottage
)
If there's not a core function, is there a simpler way of achieving this behavior? IIRC, passing variables by reference is frowned upon.
Bonus question: is there a word for the combination of both key and element from an array? I feel like 'element' doesn't necessarily include the key.
edit Since there seems to be a commonly held misunderstanding, at least in PHP 7, array_shift does not do the desired behavior. It only returns the first value, not the first element:
$ cat first_element.php
<?php
$array = [
'color' => 'red',
'car' => 'ford',
'house' => 'cottage',
];
$top = array_shift($array);
print_r($top);
print_r($array);
$ php first_element.php
redArray
(
[car] => ford
[house] => cottage
)
Try this (array_splice):
$top = array_splice($array, 0, 1);
The $top will contain the first element and the $array will contain the rest of the elements.
array_splice doesn't always preserve keys, so just get the key and combine with the result of array_shift to also remove it:
$result = [key($array) => array_shift($array)];
If needed, reset the array pointer:
reset($array) && $result = [key($array) => array_shift($array)];
function my_function($array) {
$first_key = key($array);
return array($first_key =>$array[$first_key] );
}
$array = array( 'color' => 'red', 'car' => 'ford','house' => 'cottage' );
$first = my_function($array);
array_shift($array);print_r($first);print_r($array);
I made this function:
function array_extract(array &$array, $num) {
$output = array_slice($array,0, $num);
array_splice($array,0, $num);
return $output;
}
Here's what it does
$ cat test.php
<?php
$test = [234,25,45,78,56];
echo "test:\n";
print_r($test);
while( count($test) ) {
echo "extraction:\n";
print_r(array_extract($test, 2));
echo "\ntest:\n";
print_r($test);
}
$ php test.php
test:
Array
(
[0] => 234
[1] => 25
[2] => 45
[3] => 78
[4] => 56
)
extraction:
Array
(
[0] => 234
[1] => 25
)
test:
Array
(
[0] => 45
[1] => 78
[2] => 56
)
extraction:
Array
(
[0] => 45
[1] => 78
)
test:
Array
(
[0] => 56
)
extraction:
Array
(
[0] => 56
)
test:
Array
(
)
Quite simple:
$array1 = [
'color' => 'red',
'car' => 'ford'
'house' => 'cottage',
];
$array2 = array_unshift($array1);
--> result
$array2 = [
'color' => 'red'
];
$array1 = [
'car' => 'ford'
'house' => 'cottage',
];
Assume I have an array like the one below:
Array
(
[0] => Array
(
[town_id] => 1
[town_name] => ABC
[town_province_id] => 7
)
[1] => Array
(
[town_id] => 2
[town_name] => DEF
[town_province_id] => 4
)
[2] => Array
(
[town_id] => 3
[town_name] => GHI
[town_province_id] => 2
)
)
I want to provide value "DEF" in the above array and return value "2".
Please help me.
You can use in_array to get your result.
$input = 'DEF';
foreach($array as $key=>$value){
if(in_array($input,$value)){
$town_id = $value['town_id'];
}
}
print_r($town_id);
You can use array_search with array_column
$key = array_search('DEF', array_column($array, 'town_name'));
Example:
$data = array( array('town_id' => 1, 'town_name' => 'ABC'), array('town_id' => 2, 'town_name' => 'DEF') );
print_r($data);
$key = array_search('DEF', array_column($data, 'town_name'));
print_r($data[$key]['town_id']); // it will have 2
Use array_search and array_column
$key = array_search('DEF', array_column($your_arr, 'town_name'));
$your_arr[$key]['town_id']; // should return DEF
Note: array_column works from PHP 5 >= 5.5.0
Convert these array into one array
Array ( [0] => 10 )
Array ( [0] => 17 )
Array ( [0] => 17 )
Array ( [0] => 15 )
I want an output like this:
Array ( [0] => 10 ,[1] => 17,[2] => 17,[3] => 15)
$a=array(10);$b=array(17);$c=array(17);$d=array(15);
print_r(array_merge($a,$b,$c,$d));
//Array([0]=>10 [1]=>17 [2]=>17 [3]=>15)
Assuming that your Main Array contains some sub-arrays nested within it like so:
<?php
$arrNestedArray = array(
array(10),
array(17),
array(17),
array(15),
array("data"=>array("fName"=>"Cosmic", "lName"=>"Joy")),
);
And, now; you want to take-out all the values of every element in the sub-arrays and turn them into direct elements of the Main Array. You can do that with array_walk... and then build up your Flat Array having the Structure you had anticipated like this:
<?php
// CREATE AN EMPTY ARRAY TO HOLD THE FINAL RESULT YOU DESIRED...
$singleArray = array();
// THIS IS A SAMPLE OF THE MAIN ARRAY CONTAINING SUB ARRAYS...
$arrNestedArray = array(
array(10),
array(17),
array(17),
array(15),
array("data"=>array("fName"=>"Cosmic", "lName"=>"Joy")),
);
array_walk($arrNestedArray, function($data, $index) use(&$singleArray) {
if( is_array($data) ) {
foreach ($data as $key=>$item) {
if(!in_array($item, $singleArray)) {
if(is_array($item)) {
$singleArray[$key] = $item;
}else{
$singleArray[$index] = $item;
}
}
}
}
});
var_dump($singleArray);
Finally, while you might still want to test it out here; the var_dump above produces something like this:
array (size=4)
0 => int 10
1 => int 17
3 => int 15
'data' =>
array (size=2)
'fName' => string 'Cosmic' (length=6)
'lName' => string 'Joy' (length=3)
Use array_merge with call_user_func_array:
$a = array(Array ( 0 => 10 ), Array ( 0 => 17 ), Array ( 0 => 17 ), Array ( 0 => 15 ));
$ra = call_user_func_array('array_merge', $a);
print_r($ra); // Array ( [0] => 10 [1] => 17 [2] => 17 [3] => 15 )
I have an array of arrays set up like so. There are a total of 10 arrays but I will just display the first 2. The second column has a unique id of between 1-10 (each only used once).
Array
(
[0] => Array
(
[0] => User1
[1] => 5
)
[1] => Array
(
[0] => User2
[1] => 3
)
)
I have another array of arrays:
Array
(
[0] => Array
(
[0] => 3
[1] => 10.00
)
[1] => Array
(
[0] => 5
[1] => 47.00
)
)
where the first column is the id and the second column is the value I want to add to the first array.
Each id (1-10) is only used once. How would I go about adding the second column from Array#2 to Array#1 matching the ID#?
There are tons of ways to do this :) This is one of them, optimizing the second array for search and walking the first one:
Live example
<?
$first_array[0][] = 'User1';
$first_array[0][] = 5;
$first_array[1][] = 'User2';
$first_array[1][] = 3;
$secnd_array[0][] = 3;
$secnd_array[0][] = 10.00;
$secnd_array[1][] = 5;
$secnd_array[1][] = 47.00;
// Make the user_id the key of the array
foreach ($secnd_array as $sca) {
$searchable_second_array[ $sca[0] ] = $sca[1];
}
// Modify the original array
array_walk($first_array, function(&$a) use ($searchable_second_array) {
// Here we find the second element of the first array in the modified second array :p
$a[] = $searchable_second_array[ $a[1] ];
});
// print_r($first_array);
Assuming that 0 will always be the key of the array and 1 will always be the value you'd like to add, a simple foreach loop is all you need.
Where $initial is the first array you provided and $add is the second:
<?php
$initial = array(array("User1", 5),
array("User2", 3));
$add = array(
array(0, 10.00),
array(1, 47.00));
foreach ($add as $item) {
if (isset($initial[$item[0]])) {
$initial[$item[0]][] = $item[1];
}
}
printf("<pre>%s</pre>", print_r($arr1[$item[0]], true));
I don't know if I got you right, but I've come up with a solution XD
<?php
$array_1 = array(
0 => array(
0 => 'ID1',
1 => 5
),
1 => array(
0 => 'ID2',
1 => 3
)
);
$array_2 = array(
0 => array(
0 => 3,
1 => 10.00
),
1 => array(
0 => 5,
1 => 47.00
)
);
foreach($array_1 as $key_1 => $arr_1){
foreach($array_2 as $key_2 => $arr_2){
if($arr_2[0] == $arr_1[1]){
$array_1[$key_1][2] = $arr_2[1];
}
}
}
var_dump($array_1);
?>
Demo: https://eval.in/201648
The short version would look like this:
<?php
$array_1 = array(array('ID1',5),array('ID2',3));
$array_2 = array(array(3,10.00),array(5,47.00));
foreach($array_1 as $key => $arr_1){
foreach($array_2 as$arr_2){
if($arr_2[0] == $arr_1[1]){
$array_1[$key][2] = $arr_2[1];
}
}
}
var_dump($array_1);
?>
Demo: https://eval.in/201649
Hope that helps :)
A quick and dirty way just to show you one of the more self-explaining ways to do it :)
$users = array(
0 => array(
0 => 'User1',
1 => 123
),
1 => array(
0 => 'User2',
1 => 456
)
);
$items = array(
0 => array(
0 => 123,
1 => 'Stuff 1'
),
1 => array(
0 => 456,
1 => 'Stuff 2'
)
);
foreach($items as $item){
foreach($users as $key => $user){
if($item[0] == $user[1])
array_push($users[$key], $item[1]);
}
}
I have the following array, which I would like to reindex so the keys are reversed (ideally starting at 1):
Current array (edit: the array actually looks like this):
Array (
[2] => Object
(
[title] => Section
[linked] => 1
)
[1] => Object
(
[title] => Sub-Section
[linked] => 1
)
[0] => Object
(
[title] => Sub-Sub-Section
[linked] =>
)
)
How it should be:
Array (
[1] => Object
(
[title] => Section
[linked] => 1
)
[2] => Object
(
[title] => Sub-Section
[linked] => 1
)
[3] => Object
(
[title] => Sub-Sub-Section
[linked] =>
)
)
If you want to re-index starting to zero, simply do the following:
$iZero = array_values($arr);
If you need it to start at one, then use the following:
$iOne = array_combine(range(1, count($arr)), array_values($arr));
Here are the manual pages for the functions used:
array_values()
array_combine()
range()
Why reindexing? Just add 1 to the index:
foreach ($array as $key => $val) {
echo $key + 1, '<br>';
}
Edit After the question has been clarified: You could use the array_values to reset the index starting at 0. Then you could use the algorithm above if you just want printed elements to start at 1.
This will do what you want:
<?php
$array = array(2 => 'a', 1 => 'b', 0 => 'c');
array_unshift($array, false); // Add to the start of the array
$array = array_values($array); // Re-number
// Remove the first index so we start at 1
$array = array_slice($array, 1, count($array), true);
print_r($array); // Array ( [1] => a [2] => b [3] => c )
?>
You may want to consider why you want to use a 1-based array at all. Zero-based arrays (when using non-associative arrays) are pretty standard, and if you're wanting to output to a UI, most would handle the solution by just increasing the integer upon output to the UI.
Think about consistency—both in your application and in the code you work with—when thinking about 1-based indexers for arrays.
You can reindex an array so the new array starts with an index of 1 like this;
$arr = array(
'2' => 'red',
'1' => 'green',
'0' => 'blue',
);
$arr1 = array_values($arr); // Reindex the array starting from 0.
array_unshift($arr1, ''); // Prepend a dummy element to the start of the array.
unset($arr1[0]); // Kill the dummy element.
print_r($arr);
print_r($arr1);
The output from the above is;
Array
(
[2] => red
[1] => green
[0] => blue
)
Array
(
[1] => red
[2] => green
[3] => blue
)
Well, I would like to think that for whatever your end goal is, you wouldn't actually need to modify the array to be 1-based as opposed to 0-based, but could instead handle it at iteration time like Gumbo posted.
However, to answer your question, this function should convert any array into a 1-based version
function convertToOneBased( $arr )
{
return array_combine( range( 1, count( $arr ) ), array_values( $arr ) );
}
EDIT
Here's a more reusable/flexible function, should you desire it
$arr = array( 'a', 'b', 'c' );
echo '<pre>';
print_r( reIndexArray( $arr ) );
print_r( reIndexArray( $arr, 1 ) );
print_r( reIndexArray( $arr, 2 ) );
print_r( reIndexArray( $arr, 10 ) );
print_r( reIndexArray( $arr, -10 ) );
echo '</pre>';
function reIndexArray( $arr, $startAt=0 )
{
return ( 0 == $startAt )
? array_values( $arr )
: array_combine( range( $startAt, count( $arr ) + ( $startAt - 1 ) ), array_values( $arr ) );
}
A more elegant solution:
$list = array_combine(range(1, count($list)), array_values($list));
The fastest way I can think of
array_unshift($arr, null);
unset($arr[0]);
print_r($arr);
And if you just want to reindex the array(start at zero) and you have PHP +7.3 you can do it this way
array_unshift($arr);
I believe array_unshift is better than array_values as the former does not create a copy of the array.
Changelog
Version
Description
7.3.0
This function can now be called with only one parameter. Formerly, at least two parameters have been required.
-- https://www.php.net/manual/en/function.array-unshift.php#refsect1-function.array-unshift-changelog
$tmp = array();
foreach (array_values($array) as $key => $value) {
$tmp[$key+1] = $value;
}
$array = $tmp;
It feels like all of the array_combine() answers are all copying the same "mistake" (the unnecessary call of array_values()).
array_combine() ignores the keys of both parameters that it receives.
Code: (Demo)
$array = [
2 => (object)['title' => 'Section', 'linked' => 1],
1 => (object)['title' => 'Sub-Section', 'linked' => 1],
0 => (object)['title' => 'Sub-Sub-Section', 'linked' => null]
];
var_export(array_combine(range(1, count($array)), $array));
Output:
array (
1 =>
(object) array(
'title' => 'Section',
'linked' => 1,
),
2 =>
(object) array(
'title' => 'Sub-Section',
'linked' => 1,
),
3 =>
(object) array(
'title' => 'Sub-Sub-Section',
'linked' => NULL,
),
)
If you are not trying to reorder the array you can just do:
$array = array_reverse( $array );
and then call it once more to get it back to the same order:
$array = array_reverse( $array );
array_reverse() reindexes as it reverses. Someone else showed me this a long time ago. So I can't take credit for coming up with it. But it is very simple and fast.
The result is an array with indexed keys starting from 0. https://3v4l.org/iQgVh
array (
0 =>
(object) array(
'title' => 'Section',
'linked' => 1,
),
1 =>
(object) array(
'title' => 'Sub-Section',
'linked' => 1,
),
2 =>
(object) array(
'title' => 'Sub-Sub-Section',
'linked' => NULL,
),
)
Here's my own implementation. Keys in the input array will be renumbered with incrementing keys starting from $start_index.
function array_reindex($array, $start_index)
{
$array = array_values($array);
$zeros_array = array_fill(0, $start_index, null);
return array_slice(array_merge($zeros_array, $array), $start_index, null, true);
}