PHP built in array function - php

Lets say I end up with an array like such:
Array ( [0] => Array ( [0] => user
[1] => pass
)
)
maybe as a result of passing an array through a function and using func_get_args()
In this case, I would want to get rid of the initial array, so I just end up with:
Array ( [0] => user
[1] => pass
)
I know I could make a function to accomplish this, and push each element into a new array, however, is there some built in functionality with PHP that can pull this off?

$new_array = $old_array[0];
...

array_pop() will pop the last (first, if only 1 is present) element.

Just take the value of the first element of the "outer" array.

I would recommend array_shift as it removes and returns the first element off of the beginning of the array.

Related

PHP - Store an array returned by a function in an already existing array, one by one

Very simplified example:
function returnArray() {
return array('First','Second','Third');
}
$arr = array('hello','world');
$arr[] = returnArray();
print_r($arr);
I was (wrongly) expecting to see $arr containing 5 elements, but it actually contains this (and I understand it makes sense):
Array
(
[0] => hello
[1] => world
[2] => Array
(
[0] => First
[1] => Second
[2] => Third
)
)
Easily enough, I "fixed" it using a temporary array, scanning through its elements, and adding the elements one by one to the $arr array.
But I guess/hope that there must be a way to tell PHP to add the elements automatically one by one, instead of creating a "child" array within the first one, right? Thanks!
You can use array_merge,
$arr = array_merge($arr, returnArray());
will result in
Array
(
[0] => hello
[1] => world
[2] => First
[3] => Second
[4] => Third
)
This will work smoothly here, since your arrays both have numeric keys. If the keys were strings, you’d had to be more careful (resp. decide if that would be the result you want, or not), because
If the input arrays have the same string keys, then the later value for that key will overwrite the previous one. If, however, the arrays contain numeric keys, the later value will not overwrite the original value, but will be appended.
You are appending the resulting array to previously created array. Instead of the use array merge.
function returnArray() {
return array('First','Second','Third');
}
$arr = array('hello','world');
$arr = array_merge($arr, returnArray());
print_r($arr);

How do I reorganize an array in PHP?

I am trying to figure out how to reorganize an array..
I have a multidimensional array(Ill call that original_array) and I would like to take the first array within original_array and set the values as keys in a new array. I also want to take the values of the second array in original_array and make them keys and then set the values of the third array in original_array as the values for those keys.
Here is an example of original_array:
Array (
[id] => Array (
[0] => 1
[1] => 3
)
[reward] => Array (
[0] => Movie
[1] => Trip
)
[cost] => Array (
[0] => 50
[1] => 200
)
)
Basically what I would like to do is look like this:
Array (
[1] => Array (
[Movie] => 50
)
[3] => Array (
[Trip] => 200
)
)
Is there a simple and elegant way to merge these like this?
I have spent hours trying to figure this out using array_merge, array_merge_recursive.. etc. And have search SO far and wide for a similar questions, but I haven't found anything that does what I am after.
I was able to correctly combine the 2nd and 3rd arrays in original_array with array_combine. But, I am at a loss as how to combine that result with the 1st array's values in original_array.
Thanks in advance to any help!
Well, the dirty way would be just use combine array functions like array_combine with the input:
$new_array = array_combine(
$array['id'], // parent keys
// combine chunked combined sub keys :p
array_chunk(array_combine($array['reward'], $array['cost']), 1, true)
);
There may be some incantation of array_*() merging functions that could produce what you're looking for, but it is far easier to just iterate over the original array's [id] sub-array and use its values to create new sub-array keys in a different output array.
// To hold your output
$output = array();
// Iterate the original array's [id] sub-array
foreach ($original['id'] as $idxkey => $newkey) {
// Add a sub-array using $newkey to the output array
$output[$newkey] = array(
// Using the index (not value), retrieve the corresponding reward
// value to use as the new array key
// and corresponding cost to use as the new subarray value
$original['reward'][$idxkey] => $original['cost'][$idxkey]
);
}
Here is a demonstration: https://3v4l.org/2pac3
This should work for you:
First you can get the keys for the main array into a separate variable with array_shift(), which will just remove the first element from your array, which is the array holding the keys.
Then use array_map() to loop through both of your subArrays and use reward as key with the cost values as value and return it in an array. At the end you just have to array_combine() your keys $keys with the new created array.
Code:
<?php
$keys = array_shift($arr);
$result = array_combine($keys, array_map(function($k, $v){
return [$k => $v];
}, $arr["reward"], $arr["cost"]));
print_r($result);
?>
You might wanna take a look at BaseArrayHelper from Yii 2.0 Framework.
Although this file is part of a framework it has only very few dependencies and you should be able to use just this file or parts of it in your code with small modifications.
An example for your use case can be found in the index() method.

PHP reverse the order of sub array

Here is an array example I have.
Array
(
[0] => Array
(
[0] => a
[1] => b
[2] => c
)
)
I need the order of the sub array to be reversed. I know the function I need to use is "reverse_array" but I do not know how to apply it to an array within an array.
The function you need to use is array_reverse(), but I'm assuming that's the one you were talking about. To answer your question, you simply specify the array item instead of the main array:
$array[0] = array_reverse($array[0]);
// ^ ^
If you instead wish to reverse all sub-arrays in an array, you can use array_map():
$array = array_map('array_reverse', $array);

php - how to point internal array pointer to specific element

I have an associated array who's last elements start with
[0] => value
moving onwards
[1] => value, [2] => value ... etc
But it wont be determined until run time how many elements there will be (1, 2 ,3 etc). So, I am trying to write a script which will pull off those last elements and store them in a separate array for looping. To do this, I will need to know how to point start the pointer at associated array element [0] and then continue until the end of the array.
How can I achieve this?
How about this?
<?php
$array = array("1","2","3","value","more","stuff","here");
if ($foundit = array_search("value",$array)) {
$new_array = array_slice($array,$foundit);
}
print_r($new_array);
Array
(
[0] => value
[1] => more
[2] => stuff
[3] => here
)
I'm assuming that you have control over the code that dynamically generates the elements that need to be added to your array. If this is the case, you can use PHP's array_push() function to append to the end of the existing array.
PHP Manual: array_push
PHP has no pointers, but if you need to iterate over whole array (no matter associative it or not) you can use foreach
like
foreach($array ask $key => $value)
echo $key . ' ' . $value;

PHP array_shift() not working for me. What am I doing wrong?

I am creating an array and want to delete the first element of the array and re-index it. From what I can tell, array_shift() is the right solution. However, it is not working in my implementation.
I have a member variable of my class that is defined as an array called $waypoint_city. Here is the variable output prior to shifting the array:
print_r($this->waypoint_city);
Result:
Array ( [0] => [1] => JACKSONVILLE [2] => ORLANDO [3] => MONTGOMERY [4] => MEMPHIS )
If I do the following, I get the correct result:
print_r(array_shift($this->waypoint_city));
Result:
Array ( [0] => JACKSONVILLE [1] => ORLANDO [2] => MONTGOMERY [3] => MEMPHIS )
However, if I try to reassign the result to the member variable it doesn't work... Anyone know why that is?
$this->waypoint_city = array_shift($this->waypoint_city);
If I try to print_r($this->waypoint_city) it looks like nothing is in there. Thanks to anyone who can save the hair that I haven't pulled out, yet.
array_shift[docs] changes the array in-place. It returns the first element (which is empty in your case):
Returns the shifted value, or NULL if array is empty or is not an array.
All you have to do is:
array_shift($this->waypoint_city);
That's because there IS nothing there. You have element 0 set to nothing, and array_shift returns the shifted element, which the first time through is null.
array_shift() gets its parameter as reference, so you should call array_shift() like this:
$shiftedElement = array_shift(&$this->waypoint_city);

Categories