how to use array_push() [duplicate] - php

This question already has answers here:
Add values to an associative array in PHP
(2 answers)
Closed 7 years ago.
I want to push new data in array which each value of them.
$array = array("menu1" => "101", "menu2" => "201");
array_push($array, "menu3" => "301");
But I got an error syntax.
And if I use like this :
$array = array("menu1" => "101", "menu2" => "201");
array_push($array, "menu3", "301");
result is : Array ( [menu1]=>101 [menu2]=>201 [0]=>menu3 [1]=>301 )
My hope the result is : Array ( [menu1]=>101 [menu2]=>201 [menu3]=>301 )
I want push new [menu3]=>'301' but I dont know how. Please help me, the answer will be appreciate

You can use
$array["menu3"] = "301"
as for array_push
array_push() treats array as a stack, and pushes the passed variables onto the end of array
so for associative arrays is a no match
another suitable function for what you want but it requires an array argument is array_merge
$result = array_merge(array("one" => "1"), array("two" => "2"));

Related

How can I get values from two different arrays to one array? [duplicate]

This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 9 months ago.
I have this array. I want to get the array values to a same array,how can I achieve that?
Array
(
[0] => Array
(
[referrer_id] => usr157
)
[1] => Array
(
[referrer_id] => usr42
)
)
I want this array to be
array("usr157", "usr42")
use array_walk_recursive to achieve the result as follows
<?php
$main = [];
$ref =
[
[
"referrer_id" => "usr157"
],
[
"referrer_id" => "usr42"
]
];
array_walk_recursive($ref, function ($item, $key) use(&$main) {
$main[] = $item;
} );
print_r($main);
You can check that out here
You can just access the array components like this:
// The next line just recreates your example array into a variable called $x:
$x = array(array('referrer_id' => 'usr157'), array('referrer_id' => 'usr42'));
$result = array($x[0]['referrer_id'], $x[1]['referrer_id']);
print_r($result); //print the result for correctness checking
$result will be the output array you wanted.
Using $x[0], you refer the first element of your input array (and hence, $x[1] the second one, ...). Adding ['referrer_id'] will access its referrer_id key. The surrounding array(...) puts the values into an own array.
You can "automate" the whole thing in case you have a bigger input array using a loop.
You may use array_column to achieve that
$flatten = array_column($array, 'referrer_id');
You can also use array_map and array_values together.
$array = [
[
"referrer_id" => "usr157"
],
[
"referrer_id" => "usr42"
]
];
$flatten = array_map(function($item) {
return array_values($item)[0];
}, $array);
var_dump($flatten);
Also you can use the one-liner if you're using latest version of php that support arrow function
$flatten = array_map(fn($item) => array_values($item)[0], $array);
Or without array_values, you may specify the key
$flatten = array_map(fn($item) => $item['referrer_id'], $array);
You can see the demo here

Pushing array into multidimensional array (php) [duplicate]

This question already has an answer here:
array_push won't give an array, prints out integer value
(1 answer)
Closed 4 years ago.
I've attempted many different ways to push an array into a multidimensional array, including array_push(), $array['index'] = $toPush but I keep being met with quite unexpected results. I have used both var_dump() and print_r() as detailed below in an attempt to debug, but cannot work out the issue.
My reasoning behind is to run a while loop to pull game id's and game names and store these in an assoc. array, and then push them into my main array.
$games_array = array
(
"games" => array
(
array("id"=>"1", "game"=>"first game");
array("id"=>"2", "game"=>"second game");
)
);
// a while loop would run here and update $game_to_add;
$game_to_add = array("id"=>"$game['id']", "game"=>"$game['title']");
$games_array = array_push($games_array['games'], $game_to_add);
In this example, the while() would update the ID and the Game inside of $game_to_add
But, whenever I attempt this it simply overwrites the array and outputs an integer ( example: int(3) )
I don't understand what the problem is, any explination would be appreciated as I cannot find a question specifically for this.
My actual test code:
$games_array = array( "games" => array(
array("id" => "1", "name" => "Star feathers"),
array("id" => "2", "name" => "chung fu")
)
);
$another_game = array("id" => "3", "name" => "some kunt");
$games_array = array_push($games_array["games"], array("id" => "3", "name"
=>"some game"));
var_dump($games_array);
You're assigning the return value of array_push to the games array.
The return value of array_push is the amount of elements after pushing.
Just use it as
array_push($array, $newElement);
(Without assignment)
If you're only pushing one element at he time, $array[] = $newElement is preferred to prevent overhead of the function call of array_push

Why is this PHP array not the same? [duplicate]

This question already has answers here:
How can I access an array/object?
(6 answers)
Closed 4 months ago.
I'm not understanding why the array:
<? $data = array( 'items[0][type]' => 'screenprint'); ?>
Is not the same as
<? echo $data['items'][0]['type']; ?>
I'm trying to add to the array but can't seem to figure out how?
array( 'items[0][type]' => 'screenprint')
This is an array which has one key which is named "items[0][type]" which has one value. That's not the same as an array which has a key items which has a key 0 which has a key type. PHP doesn't care that the key kinda looks like PHP syntax, it's just one string. What you want is:
$data = array('items' => array(0 => array('type' => 'screenprint')));
I hope it's obvious that that's a very different data structure.
It should be:
$data = [
'items' => [['type' => 'screenprint']]
];
echo $data['items'][0]['type'];

Get all values of a specific column in a multidimensional array [duplicate]

This question already has answers here:
How to get an array of specific "key" in multidimensional array without looping [duplicate]
(4 answers)
Closed 1 year ago.
I have a multidimensional array, that has say, x number of columns and y number of rows.
I want specifically all the values in the 3rd column.
The obvious way to go about doing this is to put this in a for loop like this
for(i=0;i<y-1;i++)
{
$ThirdColumn[] = $array[$i][3];
}
but there is an obvious time complexity of O(n) involved here. Is there a built in way for me to simply extract each of these rows from the array without having to loop in.
For example (this does not work offcourse)
$ThirdColumn = $array[][3]
Given a bidimensional array $channels:
$channels = array(
array(
'id' => 100,
'name' => 'Direct'
),
array(
'id' => 200,
'name' => 'Dynamic'
)
);
A nice way is using array_map:
$_currentChannels = array_map(function ($value) {
return $value['name'];
}, $channels);
and if you are a potentate (php 5.5+) through array_column:
$_currentChannels = array_column($channels, 'name');
Both results in:
Array
(
[0] => Direct
[1] => Dynamic
)
Star guests:
array_map (php4+) and array_column (php5.5+)
// array array_map ( callable $callback , array $array1 [, array $... ] )
// array array_column ( array $array , mixed $column_key [, mixed $index_key = null ] )
Is there a built in way for me to simply extract each of these rows from the array without having to loop in.
Not yet. There will be a function soon named array_column(). However the complexity will be the same, it's just a bit more optimized because it's implemented in C and inside the PHP engine.
Try this....
foreach ($array as $val)
{
$thirdCol[] = $val[2];
}
Youll endup with an array of all values from 3rd column
Another way to do the same would be something like $newArray = array_map( function($a) { return $a['desiredColumn']; }, $oldArray ); though I don't think it will make any significant (if any) improvement on the performance.
You could try this:
$array["a"][0]=10;
$array["a"][1]=20;
$array["a"][2]=30;
$array["a"][3]=40;
$array["a"][4]=50;
$array["a"][5]=60;
$array["b"][0]="xx";
$array["b"][1]="yy";
$array["b"][2]="zz";
$array["b"][3]="aa";
$array["b"][4]="vv";
$array["b"][5]="rr";
$output = array_slice($array["b"], 0, count($array["b"]));
print_r($output);

How to get key value of array? [duplicate]

This question already has answers here:
Getting the key of the only element in a PHP array
(6 answers)
Closed 8 years ago.
How do I get the value of a key of any array item? Like how a foreach loop turns it into $k => $v...except I only want to do that once, so no need for a loop. Do I really need to make a new array that it flips to?
Take this for example.
1 => array(
'street' => 'Street Address ',
'town' => 'Town/City '
),
2 => array(
'state' => 'State '
),
Those are arrays inside a bigger array. And now I tried to do this
array_flip($thatarrayupthere[2]['state'])
What I want to receive from that is "state" because that is the key name. But I'm getting errors.
I'm not exactly sure what you wan't, but if you just want to get the key of the second array in any given array this might help.
$key = key($array[2]);
In your example above you will get "state" in your $key variable.
$key = array_keys($array[2]);
print_r($key);
ref: http://php.net/manual/en/function.array-keys.php

Categories