storing multiple values in same array with same index - php

If I want to add multiple values in array having same index in PHP, then can it be possible to create this type of an array? For e.g.,
fruits[a]="apple";
fruits[a]="banana";
fruits[a]="cherry";
fruits[b]="pineapple";
fruits[b]="grappes";
I want array to look like as below:-
fruits = {[a]=>"apple",[a]=>"banana",[a]=>"cherry",[b]=>"pineapple",[b]=>"grappes"};

You cannot define multiple value under same key or index.
In your case -
fruits[a]="apple";
fruits[a]="banana";
Here apple will be replaced by banana.
Instead, you may define array as -
fruits[a][] = "apple";
fruits[a][] = "banana";

Edit: i updated my answer with php code, but i don't code php usually, this might not be the most optimal solution, i tried this code in a php sandbox
$subarray1[0] = "apple";
$subarray1[1] = "banana";
$subarray1[2] = "cherry";
$subarray2[0] = "pineapple";
$subarray2[1] = "grappes";
$fruits[0] = $subarray1;
$fruits[1] = $subarray2;
foreach( $fruits as $key => $value ){
foreach( $value as $key2 => $value2 ){
echo $key2."\t=>\t".$value2."\n";
}
}

use implode and explode .
subarray1[0] = "apple"
subarray1[1] = "banana"
subarray1[2] = "cherry"
subarray2[0] = "pineapple"
subarray2[1] = "grappes"
It is store data with ,(comma)
$ar="";
for($i=0;$i<=count(subarray1);$i++)
{
$ar[]=subarray1[$i];
}
$rt=implode(',',$ar);
echo $rt;
It is Remove ,(comma) form array
$ex=explode(",",$ar);
print_r($ex);

Related

Set variable from an array in Laravel

The dump of the following array is:
$quest_all = $qwinners->pluck('id', 'qcounter')->toArray();
array(2) { [60]=> int(116) [50]=> int(117) }
As shown above, the key is 60 and 50 (which is qcounter), while the value is 116 and 117 (which is id).
I'm trying to assign the qcounter to a variable as follows, but with a fixed index, such as 0,1,2,3 .. etc :
$qcounter1= $quest_all[0];
$qcounter2= $quest_all[1];
And the same with id :
$id1= $quest_all[0];
$id2= $quest_all[1];
Any help is appreciated.
Try as below:
One way is:
array_values($quest_all); will give you an array of all Ids
array_keys($quest_all); will give an array of all qcounters and respective indexes for qcounter and ids will be the same.
Other way, First get all qcounters only from collection:
$quest_all = $qwinners->pluck('qcounter')->toArray();
$qcounter1= $quest_all[0];
$qcounter2= $quest_all[1];
...
and so on
Then get all ids
$quest_all = $qwinners->pluck('id')->toArray();
$id1= $quest_all[0];
$id2= $quest_all[1];
...
and so on
You can also use foreach to iterate through the result array.
To reset array keys, use array_values().
To get array keys, use array_keys():
$quest_all = $qwinners->pluck('id', 'qcounter')->toArray();
$quest_all_keys = array_keys($quest_all);
$quest_all_values = array_values($quest_all);
Or simply use foreach():
$keys = [];
$values = [];
foreach($quest_all as $key => $value){
$keys[] = $key;
$values[] = $value;
}
I am not sure why you want variable names incrementing when you could have an array instead but if you don't mind an underscore, '_' in the name and them starting at 0 index you can use extract to create these variables. (As an exercise)
$quest_all = ...;
$count = extract(array_keys($quest_all), EXTRA_PREFIX_ALL, 'qcounter');
extract(array_values($quest_all), EXTRA_PREFIX_ALL, 'id');
// $qcounter_0 $qcounter_1
// $id_0 $id_1
for ($i = 0; $i < $count; $i++) {
echo ${'qcounter_'. $i} .' is '. ${'id_'. $i} ."\n";
}
It would probably be easier to just have the 2 arrays:
$keys = array_keys($quest_all);
$values = array_values($quest_all);

PHP get first and forth value of an associative array

I have an associative array, $teams_name_points. The length of the array is unknown.
How do I access the first and forth value without knowing the key of this array in the easiest way?
The array is filled like this:
$name1 = "some_name1";
$name2 = "some_name2";
$teams_name_points[$name1] = 1;
$teams_name_points[$name2] = 2;
etc.
I want to do something like I do with an indexed array:
for($x=0; $x<count($teams_name_points); $x++){
echo $teams_name_points[$x];
}
How do I do this?
use array_keys?
$keys = array_keys($your_array);
echo $your_array[$keys[0]]; // 1st key
echo $your_array[$keys[3]]; // 4th key
You can use array_values which will give you a numerically indexed array.
$val = array_values($arr);
$first = $val[0];
$fourth = $val[3]
In addition to the array_values, to loop through as you show:
foreach($teams_name_points as $key => $value) {
echo "$key = $value";
}
You can get use the array_keys function such as
//Get all array keys in array
$keys = array_keys($teams_name_points);
//Now get the value for 4th key
//4 = (4-1) --> 3
$value = $teams_name_points[$keys[3]];
You can get all values now as exists
$cnt = count($keys);
if($cnt>0)
{
for($i=0;$i<$cnt;$i++)
{
//Get the value
$value = $team_name_points[$keys[$i]];
}
}

PHP arrays & variable variables

With an array $s_filters that looks like this (many different keys possible):
Array
(
[genders] => m
[ages] => 11-12,13-15
)
How can I programatically convert this array to this:
$gender = array('m');
$ages = array('11-12','13-15');
So basically loop through $s_filters and create new arrays the names of which is the key and the values should explode on ",";
I tried using variable variables:
foreach( $s_filters as $key => $value )
{
$$key = array();
$$key[] = $value;
print_r($$key);
}
But this gives me cannot use [] for reading errors. Am I on the right track?
The following code takes a different approach on what you're trying to achieve. It first uses the extract function to convert the array to local variables, then loops though those new variables and explodes them:
extract($s_filters);
foreach(array_keys($s_filters) as $key)
{
${$key} = explode(",", ${$key});
}
$s_filters = Array
(
"genders" => "m",
"ages" => "11-12,13-15"
);
foreach($s_filters as $key=>$value)
{
${$key} = explode(',', $value);
}
header("Content-Type: text/plain");
print_r($genders);
print_r($ages);
$gender = $arr['gender'];
What you want there is unreadable, hard to debug, and overall a bad practice. It definitely can be handled better.

Cleanest way of working out next variable name based on sequential order?

Hope my title explains it ok! Here's more detail:
I'm creating an array which stores keys & their values. Eg.
test1 = hello
test2 = world
test3 = foo
What is the cleanest way of working out what to call the next key? Let's say I will know the first part is 'test', but I don't know what the highest value number is. Obviously in this case I want it to be called 'test4'.
In the example below I want the next key to be 'test46', as it is the next highest value:
test6 = blah
test45 = boo
test23 = far
This sounds like you should be using an array with numerical indexes instead.
You could however use some code like this...
$arr = array('test6', 'test45', 'test23');
$max = 0;
foreach($arr as $value) {
$number = filter_var($value, FILTER_SANITIZE_NUMBER_INT);
$max = max($max, $number);
}
$newKey = 'test' . ++$max; // string(6) "test46"
CodePad.
Implementation of #alex answer without using a loop:
$arr = array('test6', 'test45', 'test23');
$max = max(filter_var_array($arr, FILTER_SANITIZE_NUMBER_INT));
$newKey = 'test' . ++$max; // string(6) "test46"
CodePad
This data structure would be better stored as an array.
$test = array();
$test[] = 'hello';
$test[] = 'world';
$test[] = 'foo';
You then don't need to know the highest number to add a new item, just use the empty brackets syntax (shown above) to add an item to the end of the array.
You then have access to a wealth of array functions that PHP gives you to work with your data: http://php.net/manual/en/ref.array.php
When you want to get item 43 from the array, use:
echo $test[42];
Arrays are counted from 0 rather than 1, so item 43 will have an index of 42.
What are you using that for? If numbering the array is a must-have, just use a simple numerical indexed array instead, and simply prepend the key with "test" if you need it to show up as "test1":
<?php
$array = array(
6 => 'blah',
45 => 'boo',
23 => 'bar'
);
$array[] = 'new';
echo $array[46] . "\n"; // this is 'new'
foreach( $array as $key => $value ) {
echo "test$key = $value<br />\n"; // test6 = blah
}

PHP get the item in an array that has the most duplicates

I have an array of strings and I am looking for a way to find the most common string in the array.
$stuff = array('orange','banana', 'apples','orange');
I would want to see orange.
$c = array_count_values($stuff);
$val = array_search(max($c), $c);
Use array_count_values and get the key of the item:
<?php
$stuff = array('orange','banana', 'apples','orange', 'xxxxxxx');
$result = array_count_values($stuff);
asort($result);
end($result);
$answer = key($result);
echo $answer;
?>
Output:
orange

Categories