PHP get part of string to new array? - php

If I have an array in the following format, how can I assign part of these array values in to a new array?
(Numeric value 123 and 654 indicate that the array can be separated in these locations)
$fruits = array();
$vehicles = array();
$all_words = array ("123", "apple", ”orange”, ………, ”bannana”, ”123”, ”654”, ”car”, ”bus”, ………, ”train”, ”bike”, ”654”);
//continuous ……… Indicate there can be unknown amount of array elements.
//Also, these numeric values of 123 and 645 can be changed to something convenient
I can see that using $fruits = array_slice($array, 1, 5) I can get a portion of this array in to a new one. But if I don’t know the length of array between two numbers(123 and 654, how can I assign these values in to an new array?

You can get their index using array_search() and then use them for slicing, like this..
$index1 = array_search('123', $all_words);
$index2 = array_search('654', $all_words);
$vehicles = array_slice($array, $index1, $index2-$index1+1);

$fruits = array_slice($array, array_search('123', $array)+1, array_search('654', $array)+1)

Related

Convert One dimentional Array to Multidimentional array in PHP

In PHP I have a dynamic 1-D Array which is like
$array = ['test1', 'test2', ..., 'testn'] And I need to convert this into a multidimensional array where array nesting level will be equal to the number of elements in the 1-D array, and each level will have its index with the name of 1-D array values, so, the output should be something like:
$multidimentional['test1']['test2'][...]['testn'] = [Some Fixed Value] And, after creating the multidimensional array assign a fixed value to it.
So, basically this fixed value needs to be assigned in a multidimensional array which has nesting level as per 1-D array values.
You can simply loop over the elements, assign the element as key to the current array and move on with the child array.
<?php
$array = ['test1', 'test2','test3', 'test4'];
$res = [];
$temp = &$res;
foreach($array as $val){
$temp[$val] = [];
$temp = &$temp[$val];
}
$temp[] = 45; // some fixed value
print_r($res);
Demo: https://3v4l.org/INfR2

How to push array elemnt to specific position in another array using php

I want to push new array to another array at specific position for this purpose I used array_splice followed some stackoverflow links but it didn't work for me
I refered this links also but they mentioned only for single value not array.
How to insert element into arrays at specific position?
Insert new item in array on any position in PHP
Example:
$array_1 = array(1,2,3,4,5);
$array_2 = array(a,b,c);
Now I want to push $array_2 values in $array_1 at certain position like:
a at position 1
b at position 3
c at position 4
Expected output:
$final_array=(1,a,2,b,c,3,4,5);
You need to define positions as array and combine it with array_2. Now iterate over this combined array and use code of first reference thread:
<?php
$array_1 = array(1,2,3,4,5);
$array_2 = array('a','b','c');
//define positions array
$positions = array(1,3,4);
//combine position array with $array_2
$positionArray = array_combine($positions, $array_2);
//iterate over combined array
foreach($positionArray as $key => $value){
//use code of first example thread
array_splice($array_1, $key, 0, $value);
//here $key is position where you want to insert
}
print_r($array_1);
Output: https://3v4l.org/Djar2

How to get the exact value of the last array index in PHP?

Currently i have an array $newArr with some elements as shown in picture below. How do I know the last digit of the array index (highlighted in yellow)?
This is important because, if later I wanted to insert a new record into this $newArr array, I could just
$newArr[$the_variable_that_holds_the_last_digit + 1] = ['foo', 'bar'];
otherwise the whole array overwrite if
$newArr = ['foo', 'bar'];
I think you are looking for end pointer
$array = array(
'a' => 1,
'b' => 2,
'c' => 3,
);
end($array); // it will point to last key
$key = key($array); // get the last key using `key`
Assuming you have the numerically indexed array, the last index on your array is :
$last_index = count($newArr) -1;
if However your keys are not sequential, you can do this:
end($newArr);
$last_key = key($newArr);
I think you can try this
$array = end($newArr);
$last_index = key($array);//Its display last key of array
For more details, please follow this link.
If the only reason is to not overwrite the values you can use [] which means add new value.
$arr = [1,2,3,4];
var_dump($arr);
// incorrect way:
$arr = [1,2];
var_dump($arr);
//correct way
$arr = [1,2,3,4];
$arr[] = [1,2];
var_dump($arr);
See here for output: https://3v4l.org/ZTg28
The "correct way" will in the example above input a new array in the array.
If you want to add only the values you need to insert them one at the time.
$arr[] = 1;
$arr[] = 2;

Php merge object array getting wrongly only merge last values

I am trying to merge an object as follows from set of values which comes from database as follows:
$pooldetails = array();
$qstncount = 5;
for($i=0;$i<$qstncount;$i++){
$stdClass = $DB->get_record_sql("SELECT * FROM {pool_objective} po WHERE (po.id = $randarray[$i])");
$pooldetails = (object) array_merge((array) $pooldetails, (array) $stdClass);
}
When I print outside as follows:
print_r($pooldetails);
I am getting only last value in this array. I mean the value of $qstncoun=4 .First 4 values are missing.What I am doing wrong?
It's expected actually. Quoting the docs:
If the input arrays have the same string keys, then the later value
for that key will overwrite the previous one.
To get the results combined, use array_merge_recursive() instead:
$arr1 = ['a' => 1];
$arr2 = ['a' => 2];
var_dump(array_merge($arr1, $arr2));
// ['a' => 2]
var_dump(array_merge_recursive($arr1, $arr2));
// ['a' => [1, 2]]
Be aware, however, of the following:
If the input arrays have the same string keys, then the values for
these keys are merged together into an array, and this is done
recursively, so that if one of the values is an array itself, the
function will merge it with a corresponding entry in another array
too. If, however, the arrays have the same numeric key, the later
value will not overwrite the original value, but will be appended.
It probably doesn't matter in your case, however, as keys map to column names. So you can use something like...
$pooldetails = array();
$qstncount = 5;
for($i=0;$i<$qstncount;$i++){
$stdClass = $DB->get_record_sql("SELECT * FROM {pool_objective} po WHERE (po.id = $randarray[$i])");
$pooldetails = array_merge_recursive($pooldetails, (array) $stdClass);
}
$pooldetails = (object) $pooldetails;

change starting index when assigning one array to another in php

I am using str_split() to split a long strings into an array of length 16 each. And I'm assigning the returned array to one in my function. Like this:
$myarray = str_split($string, 16);
The problem is that I want the indexing of $myarray to start from a number other than 0, say 50. Currently I'm doing this:
foreach($myarray as $id => $value)
{
$myarray[$id + 50] = $value;
unset($myarray[$id]);
}
Is there a better solution? Because the arrays and strings I'm dealing with are very long. Thanks
You can use array_pad().
$myarray = str_split($string, 16);
$myarray = array_pad($myarray, -(size($myarray)+50), null);
It will fill the first 50 elements with nulls and push the rest of the array forward by 50 elements.

Categories