I have stored many arrays in a single associative array and assigned key values simple number counting.
How can I extract one of those array from the associative array?
my array:
$arr = array(
1 => array("ask","bat","cod","dig","egg","fur","gap","hay","ice","jar","kin","lee"),
2 => array("add","big","cap","day","eye","fat","gel","hop","ink","jog","key","law"),
3 => array("axe","bin","cel","don","eat","fig","gig","hut","ion","jin","kid","lip")
);
I want to store the array indexed say 2 in $arr_chosen, what will be the syntax to do so?
$arr = array(
1 => array("ask","bat","cod","dig","egg","fur","gap","hay","ice","jar","kin","lee"),
2 => array("add","big","cap","day","eye","fat","gel","hop","ink","jog","key","law"),
3 => array("axe","bin","cel","don","eat","fig","gig","hut","ion","jin","kid","lip")
);
$arr_chosen = $arr[2];
You can extract an array by doing
$arr_chosen = $arr[2]
Related
Everyone else usually asking how to convert string array with commas to an array of key value pairs.
But my question is opposite. I want to extract the keys of the array and place them in a separate array using PHP
I have an array of this form:
Array
(
[Lights] => 4
[Tool Kit] => 4
[Steering Wheel] => 4
[Side Mirrors] => 3.5
)
and I want output to be in this form:
{"Lights", "Tool Kit", "Steering Wheel", "Side Mirrors" }
Using array_keys :
array_keys — Return all the keys or a subset of the keys of an array
So you can just extract each keys simply by using this method
$keys = array_keys($array);
Otherwise, you can loop through each values and only get the keys :
$keyArray=array_keys($array);
$keyArray=[];
foreach($array as $key => $value){
$keyArray[]=$key;
}
Use array_keys. It will return array keys as array values
$array=array('Lights' => 4,
'Tool Kit' => 4,
'Steering Wheel' => 4,
'Side Mirrors' => 3.5);
$key_array=array_keys($array);
print_r($key_array);
It will result
Array ( [0] => Lights [1] => Tool Kit [2] => Steering Wheel [3] => Side Mirrors )
Looks like you are expecting JSON output. You can just use json_encode function in a pair with array_keys.
$result = json_encode(array_keys($array));
However, your result will be ["Lights","Tool Kit","Steering Wheel","Side Mirrors"]
I want to merge many different assoc arrays in one array but in the form of assoc array. Like i have different arrays like this
Array ( [0] => abc [1] => def [2] => ghi )
Array ( [0] => jkl [1] => mno [2] => pqr )
.
.
.
and want to make an array like
array
0 =>
array
0 => string 'abc'
1 => string 'def'
2 => string 'ghi'
1 =>
array
0 => string 'jkl'
1 => string 'mno'
2 => string 'pqr'
.
.
.`
.
i am getting these arrays from a csv file. Please help. Thanks
If I understand correctly, you don't want to merge the arrays... you just want to make a multidimensional array i.e. an array of arrays. See the difference here.
You are creating the initial arrays from the csv file, but I'll create them here for completeness:
$array1 = array ( "0" => "abc", "1" => "def", "2" => "ghi" );
$array2 = array ( "0" => "jkl", "1" => "mno", "2" => "pqr" );
Then all you need to do is create an array with those arrays as the values, depending on what works with the rest of your code, e.g.
$multiarray = array();
$multiarray["0"] = $array1;
$multiarray["1"] = $array2;
or
$multiarray = array ( "0" => $array1, "1" => $array2 );
If you print_r ($multiarray);, it will look like the example in your question.
By the way, the examples you have given are not associative arrays, but I've treated them as if they are in case you do actually need them.
If your arrays are just standard indexed arrays, then you don't need to specify the key, e.g.
$array1 = new array("abc", "def", "ghi");
etc
$multiarray[] = $array1;
$multiarray[] = $array2;
I provide another point of view, which is lest optimized for the task in itself as I see it but might be useful in some context.
$array = array('abc', 'def', 'ghi');
$array2 = array('jkl', 'mno', 'pqr');
function gather(... $array){return $array;}
my_print_r(gather($array, $array2));
That function uses the splat operator, which natively gathers whatever arguments are sent to the function as entries in an array, called array in that example. We can do whatever we want with array in that function, but just by retuning it, it does what you asked for.
This question already has answers here:
Is there a function to extract a 'column' from an array in PHP?
(15 answers)
Closed 6 years ago.
I am trying to display an array without key item. Just want to display array values without key.
Here is my sample code I tried
$myList = array(
0 =>array(
"product_id"=> 8085
),
1 =>array(
"product_id"=> 8087
),
2 =>array(
"product_id"=> 8086
),
3 =>array(
"product_id"=> 8042
),
);
$newList = array();
foreach($myList as $listItem) {
$newList[] = $listItem['product_id'];
}
$a=array();
$a= array_values($newList);
print_r($a);
I want my array like this
$productIds = array(8085,8087,8086,8042);
Here is my sample code link
You're looking for array_column (which is available as of PHP 5.5):
$productIds = array_column($myList, 'product_id');
This gives you:
var_export($productIds);
array (
0 => 8085,
1 => 8087,
2 => 8086,
3 => 8042,
)
Which is exactly what you want:
var_dump($productIds === array(8085,8087,8086,8042)); // bool(true)
print_r function will output the keys. even if you use array_values the array still have indexes as keys.
Just output the the array manually using echo and implode (implode will join array values into a single string using the first parameter character):
echo implode(',', $newList);
Arrays will always have keys. If you want an array, you can get all the values, turn them into one comma separated string, and place that into an array:
$productIds = [implode(',', array_column($myList, 'product_id'))];
var_dump($productIds);
// RESULT:
// array (size=1)
// 0 => string '8085,8087,8086,8042' (length=19)
does someone know the meaning of the [ ] in the creation of a PHP array, and if it's really needed. Becasuse from my point of view. Both ways are sufficinent
Way 1, with brackets:
$cars[] = array ('expensive' => $BMW,
'medium' => $Volvo,
'cheap' => $Lada);
Way2, without brackets:
$cars = array ('expensive' => $BMW,
'medium' => $Volvo,
'cheap' => $Lada);
Read http://php.net/manual/en/function.array-push.php for a clear answer as to the differences.
main differences:
citing array() can only be done when creating the variable.
$var[] can add values to arrays that already exist.
$var[] will create an array and is in effect the same function call as $var = array(...);
also
You can not assign multiple values in a single declaration using the $var[] approach (see example 4, below).
some work throughs:
1) Using array()
$cars = "cats";
$cars = array("cars","horses","trees");
print_r($cars) ;
Will output
$cars --> [0] = cars
[1] = horses
[2] = trees
2) Appending Values
Then writing $cars = array("goats"); will NOT append the value but will instead initialise a NEW ARRAY, giving:
$cars --> [0] = goats
But if you use the square brackets to append then writing $cars[] = "goats" will give you :
$cars --> [0] = cars
[1] = horses
[2] = trees
[3] = goats
Your original question means that whatever is on the right hand side of the = sign will be appended to current array, if the left hand side has the syntax $var[] but this will be appended Numerically. As shown above.
You can append things by key name by filling in the key value: $cars['cheap'] = $Lada; .
Your example 1 is setting that an array is held within an array, so to access the value $Lada you would reference $cars[0]['cheap'] . Example 2 sets up the array but will overwrite any existing array or value in the variable.
3) String And Numerical Indexing
The method of using the array(...) syntax is good for defining multiple values at array creation when these values have non-numeric or numerically non-linear keys, such as your example:
$cars = array ('expensive' => "BMW",
'medium' => "Volvo",
'cheap' => "Lada");
Will output at array of:
$cars --> ['expensive'] = BMW
['medium'] = Volvo
['cheap'] = Lada
But if you used the alternative syntax of:
$cars[] = "BMW";
$cars[] = "Volvo";
$cars[] = "Lada";
This would output:
$cars --> [0] = BMW
[1] = Volvo
[2] = Lada
4) I'm still writing....
As another example: You can combine the effects of using array() and $var[] with key declarations within the square brackets thus:
$cars['expensive'] = "BMW";
$cars['medium'] = "Volvo";
$cars['budget'] = "Lada";
giving:
$cars --> ['expensive'] = BMW
['medium'] = Volvo
['cheap'] = Lada
(my original answer was verbose and not very great).
5) Finally.....
So what happens when you combine the two styles, mixing the array() declaration with the $var[] additions:
$ray = array("goats" => "horny", "knickers" => "on the floor", "condition" => "sour cream");
$ray[] = "crumpet";
$ray[] = "bread";
This will maintain both numeric and string key indexes in the array, outputting with print_r():
$ray --> [goats] => horny
[knickers] => on the floor
[condition] => sour cream
[0] => crumpet
[1] => bread
They are different. The first one is an array inside of another one
$cars[] = array ('expensive' => "BMW",
'medium' => "Volvo",
'cheap' => "Lada");
var_dump($cars);
array (size=1)
0 =>
array (size=3)
'expensive' => string 'BMW' (length=3)
'medium' => string 'Volvo' (length=5)
'cheap' => string 'Lada' (length=4)
The second one is just an array
$cars = array ('expensive' => "BMW",
'medium' => "Volvo",
'cheap' => "Lada");
var_dump($cars);
array (size=3)
'expensive' => string 'BMW' (length=3)
'medium' => string 'Volvo' (length=5)
'cheap' => string 'Lada' (length=4)
way 1 results an array with array values (array of array)
whereas way2 is array which contains mentioned values
Way 1 adds your new array() at the end of the existing array. So if you have 2 elements inside that array already, a third one with the array you specified will be created.
Way 2 is the typical array creation - just that some other variables are used to fill the fields.
Simply to complete your exercise, here is way 3:
$arr = array();
$arr[1] = array("foo"=>"bar");
This puts the foo:bar array at entry #1 into the $arr variable.
The second example is clear. In the first example you are adding an array element without specifying its key, hence the empty brackets []. As the array is not yet initialized, its created at the same time. The result is, as others already pointed out, a multidimensional array.
Beware though that the first way is not encouraged:
If $arr doesn't exist yet, it will be created, so this is also an alternative way to create an array. This practice is however discouraged because if $arr already contains some value (e.g. string from request variable) then this value will stay in the place and [] may actually stand for string access operator. It is always better to initialize variable by a direct assignment.
If $cars was already set, e.g. to a string, you would get an error.
$cars = 'test';
$cars[] = array ('expensive' => $BMW,
'medium' => $Volvo,
'cheap' => $Lada);
Method 1, with brackets: Multidimensional array
Array ( [0] => Array ( [expensive] => 12 [medium] => 13 [cheap] => 14 ) )
Method 2, with brackets: Associative array
Array ( [expensive] => 12 [medium] => 13 [cheap] => 14 )
I am new to php. Please let me know how do I count number of array entry in under array 80cb936e55e5225cd2af.
array
'status' => int 1
'msg' => string '2 out of 1 Transactions Fetched Successfully' (length=44)
'transaction_details' =>
array
'80cb936e55e5225cd2af' =>
array
0 =>
array
...
1 =>
array
...
Assuming your array variable is $arr : ...
$count = count($arr['transaction_details']['80cb936e55e5225cd2af']);
(But this will only count the indexes/integers of that sub-array, not the values inside them!)
You can use PHP's count() like this
$noOfEntries = count($array['transaction_details']['80cb936e55e5225cd2af']);
This will get you the number of arrays inside 80cb936e55e5225cd2af (not the overall amount of elements).