I'm trying to learn some basic PHP but am running into some confusion around using arrays.
I have three "pools" of words. 20 words in each pool for a total of 60 words.
I need to store these in separate arrays, and then pull out a random selection from the array on click of a button. So each time the button is clicked, another four will be pulled from my array of 20 entries.
You can see my non-functioning page here: http://francesca-designed.me/create-a-status/
So the words on the side, when you click the button it'd run through the 20 words in the array and output them in each span, just four each time you click the button.
I looked on the PHP site and found this but I'm confused about which one to use.
Ultimately I would like to add this to a database as in the end if will be 50 words per pool, but for now I want to keep it all in one place while I practice.
<?php
$fruits = array (
"fruits" => array("a" => "orange", "b" => "banana", "c" => "apple"),
"numbers" => array(1, 2, 3, 4, 5, 6),
"holes" => array("first", 5 => "second", "third")
);
?>
There are two types of arrays:
array(
'key' => 'value',
'key' => 'value',
'key' => 'value',
)
and
array(
'value',
'value',
'value',
'value',
);
the latter is the same as:
array(
0 => 'value',
1 => 'value',
2 => 'value',
3 => 'value',
);
it's really how you want to use them...
if you loop through them with
foreach($array as $value) {
}
or
foreach($array as $key => $value) {
}
and there is no need for named keys, just use the second array.
edit:
$array = array(
'one' => array ('qwe1rty1','qwe1rty2','qwe1rty3'),
'two' => array ('qwe2rty1','qwe2rty2','qwe2rty3'),
'three' => array ('qwe3rty1','qwe3rty2','qwe3ert3'),
);
$array['one'][2] === 'qwe1rty3' (index starts at 0)
$array['three'][0] === 'qwe3rty1'
foreach($array['one'] as $key => $value) {
echo $key .' : ' $value;
}
gives
0 : qwe1rty1
1 : qwe1rty2
2 : qwe1rty3
Here is an example that is similar to what you're describing:
$words = array("tasty", "wretched", "simple", "gnarly", "fruitful", "cleeeever");
echo $words[1]; //prints wretched
for($i=0;$i<4;$i++) {//prints array in original order
echo $words[$i].'<br/>';
}
shuffle($words);
for($i=0;$i<4;$i++) {//prints shuffled array
echo $words[$i].'<br/>';
}
Related
Short: Is there a way to get a named key/value from SUBARRAY without knowing the main key ?
Long:
Ive got a foreach loop that extracts text-files & turns them into individual / single arrays (resetting the array between each file)...
example:
Array
(
[Blah Blah] => Array
(
[number] => 10
[name] => nameBlah
[image] =>
)
)
Array
(
[pinkblue597] => Array
(
[number] => 18
[name] => nameBlah68
[image] =>
)
)
(the 1st part to turn into array is used by multiple parts of a process so I dont want to add unnecessary code)
I want to extract the value of "name" and "number", however I do not know the value / format of the key in advance.. - Example: pinkblue597
If I do print_r, I do see the array as I want...
print_r($found,true)."\n";
but if I do this, $name=$found[0]; I get no results for "$name"...
or
if I do this, $name=$found[0]["name"]; I get no results for "$name"...
I could do this via a foreach loop, but it seems inefficient...
PS there will only be ONE (unknown) key in this array, & a sub-array. The sub array is always the same.
Edited: made the code easier to see (forgot to do this)
If the array formation is going to be the same all the time...
then a (nested) foreach loop will suffice, take the example below,
<?php
$a = [
'somethingUnknown13582563' => [
'name' => 'name',
'number' => 15
],
'somethingUnknown2' => [
'name' => 'another name',
'number' => 24
]
];
foreach ($a as $key => $subArray) {
foreach ($subArray as $subKey => $value) {
echo $subArray[$subKey] . '<br>';
}
}
?>
Output
name
15
another name
24
Or...
You could use array_values,
<?php
$a = [
'somethingUnknown13582563' => [
'name' => 'first name',
'number' => 15
],
'somethingUnknown2' => [
'name' => 'name',
'number' => 24
]
];
$a = array_values($a);
echo $a[0]['name'];
?>
Which would turn the first associative array in to numeric indexes and would like so,
array(
0 => array(
'name' => 'first name',
'number' => 15,
),
1 => array(
'name' => 'name',
'number' => 24,
)
)
I'm not sure why you're creating a nested array in the first place if you only intend to discard it immediately, but since the array only appears to have a single element, and you only care about that element, you can simple use array_pop
$a = [
'somethingUnknown13582563' => [
'name' => 'first name',
'number' => 15
],
];
$data = array_pop($a);
echo $data['name']; // gives you 'first name'
Note that array_pop is destructive. So if you don't want this behavior you could use something like end instead.
$data = end($a); // same effect as array_pop but non-destructive
echo $data['name']; // also gives you 'first name'
With that said, the foreach construct isn't necessarily inefficient. I believe your true concern is around finding a simpler way to dereference the nested array. The easiest way to do that in your case is going to be using something like end($a)['name'] which gives you the kind of straight-forward dereferencing you're looking for.
You can use array_map() to achieve this...
array_map — Applies the callback to the elements of the given arrays. This will loop all the array elements through callback function and you can print each element present in the sub array..
<?php
$myArry = array(
'Blah Blah' => array(
'number' => 10,
'name' => 'Blah Blah 1',
),
'pinkblue597' => array(
'number' => 15,
'name' => 'Blah Blah 2',
)
);
array_map(function($arr){
echo 'Name : '.$arr['name'].'<br>';
echo 'Number : '.$arr['number'].'<br>';
},$myArry);
?>
This will give you :
Name : Blah Blah 1
Number : 10
Name : Blah Blah 2
Number : 15
So I have two array, the first one is like:
$MyArray = [
['id' => 1, number => 32],
['id' => 2, number => 4]
];
and the other is like:
$OtherArray = [
['id' => 1, 'show' => X],
['id' => 5, 'show' => X]
];
Where is X, I want it to be equal with the 'number' value of $MyArray where key 'id' = its id.
If there is no $MyArray.id which is equal to $OtherArray.id then it should return 0.
I hope you understand what I mean. I tried everything, what I could, yet, with no success.
Have you tried using a foreach loop here?
Here is a quick example... PHPaste Snippet
<?php
$firstArray = array(
array(
"id" => 1,
"something" => "Hello, World!"
),
array(
"id" => 3, // 3 on purpose
"something" => "Hello, mom?"
)
);
$secondArray = array(
array(
"id" => 1,
"thing" => null
),
array(
"id" => 2,
"thing" => null
)
);
foreach ($firstArray as $key => $value) {
foreach ($secondArray as $k => $v) {
if ($value['id'] == $v['id']) {
echo "Found one!\n------\n" . print_r($value, true) . "\ncontains the same ID as\n\n" . print_r($v, true) . "\n------\n";
// you may also do this if you want
// $secondArray[$k]['thing'] = $value['id'];
// this would set "thing" (in the second array) to the value of "id" (in the first array)
}
}
}
EDIT Here is a second example, displaying how you could use it as a function... PHPaste Snippet.
Note: I used the OLD array syntax because it's easier for new programmers to understand.
So, essentially what you are doing is iterating through each item in $firstArray, comparing it to each item in $secondArray, by doing a nested foreach within side the first foreach if that makes sense...?
Here is what I just said in simple form:
go through each item in array 1
--> compare it to each item in array 2
You may also notice my use of PHP's lovely function, print_r(). This displays objects and arrays in a slightly, clearer, form.
You can also see that I am getting the values from within the arrays by using $value['id'] and $v['id']. These were defined in my foreach declaration, foreach ($firstArray as $key => $value); $value is an associative array, so you can simply get a value by key just as you would if you created an array like this:
$myArray = [
"id" => 1
];
and grabbed values like this:
echo $myArray['id']; // 1
Hopefully this helped.
I have a variable number of multidimensional arrays but all with the same 4 possible values for each item.
For example:
Array
(
[companyid] => 1
[employeeid] => 1
[role] => "Something"
[name] => "Something"
)
but every array may have a different ammount of items inside it.
I want to turn all the arrays into one single table with lots of rows. I tried array_merge() but I end up with a table with 8, 12, 16... columns instead of more rows.
So... any ideas?
Thanks
Didn't test it, but you could try the following:
$table = array();
$columns = array('companyid' => '', 'employeeid' => '', 'role' => '', 'name' => '');
foreach($array as $item) {
$table[] = array_merge($columns, $item);
}
This should work since the documentation about array_merge say:
If the input arrays have the same string keys, then the later value
for that key will overwrite the previous one.
So you either get the value of the current item or a default value that you can specify in the $columns array.
$array1=Array
(
"companyid" => 1,
"employeeid" => 4,
"role" => "Something",
"name" => "Something",
);
$array2=Array
(
"companyid" => array(2,2,2),
"employeeid" => 5,
"role" => "Something2",
"name" => "Something2"
);
$array3=Array
(
"companyid" => 3,
"employeeid" => 6,
"role" => "Something3",
"name" => "Something3"
);
//Using array_merge
$main_array["companyid"]=array_merge((array)$array1["companyid"],(array)$array2["companyid"],(array)$array3["companyid"]);
$main_array["employeeid"]=array_merge((array)$array1["employeeid"],(array)$array2["employeeid"],(array)$array3["employeeid"]);
for($i=0;$i<count($main_array["companyid"]);$i++)
echo $main_array["companyid"][$i] + "<br />";
for($i=0;$i<count($main_array["employeeid"]);$i++)
echo $main_array["employeeid"][$i] + "<br />";
I've tested the code above and seems right.
You coult also improve this code into a DRY function.
I have two arrays
they look like
$a1 = array(
array('num' => 1, 'name' => 'one'),
array('num' => 2, 'name' => 'two'),
array('num' => 3, 'name' => 'three'),
array('num' => 4, 'name' => 'four'),
array('num' => 5, 'name' => 'five')
)
$a2 = array(3,4,5,6,7,8);
I want to end up with an array that looks like
$a3 = array(3,4,5);
so basically where $a1[$i]['num'] is in $a2
I know I could do
$a3 = array();
foreach($a1 as $num)
if(array_search($num['num'], $a2))
$a3[] = $num['num'];
But that seems like a lot of un-needed iterations.
Is there a better way?
Ah Snap...
I just realized I asked this question the wrong way around, I want to end up with an array that looks like
$a3 array(
array('num' => 3, 'name' => 'three'),
array('num' => 4, 'name' => 'four'),
array('num' => 5, 'name' => 'five')
)
You could extract the relevant informations (the 'num' items) from $a1 :
$a1_bis = array();
foreach ($a1 as $a) {
$a1_bis[] = $a['num'];
}
And, then, use array_intersect() to find what is both in $a1_bis and $a2 :
$result = array_intersect($a1_bis, $a2);
var_dump($result);
Which would get you :
array
2 => int 3
3 => int 4
4 => int 5
With this solution :
you are going through $a1 only once
you trust PHP on using a good algorithm to find the intersection between the two arrays (and/or consider that a function developed in C will probably be faster than any equivalent you could code in pure-PHP)
EDIT after the comment : well, considering the result you want, now, I would go with another approach.
First, I would use array_flip() to flip the $a2 array, to allow faster access to its elements (accessing by key is way faster than finding a value) :
$a2_hash = array_flip($a2); // To speed things up :
// accessing by key is way faster than finding
// an item in an array by value
Then, I would use array_filter() to apply a filter to $a1, keeping the items for which num is in the $a2_hash flipped-array :
$result = array_filter($a1, function ($item) use ($a2_hash) {
if (isset($a2_hash[ $item['num'] ])) {
return true;
}
return false;
});
var_dump($result);
Note : I used an anonymous function, which only exist with PHP >= 5.3 ; if you are using PHP < 5.3, this code can be re-worked to suppress the closure.
With that, I get the array you want :
array
2 =>
array
'num' => int 3
'name' => string 'three' (length=5)
3 =>
array
'num' => int 4
'name' => string 'four' (length=4)
4 =>
array
'num' => int 5
'name' => string 'five' (length=4)
Note the keys are not corresponding to anything useful -- if you want them removed, just use the array_values() function on that $result :
$final_result = array_values($result);
But that's probably not necessary :-)
I want to create a twodimensional array in php. What is the correct syntax of creating an empty multidimensional array in php.
Secondly I want to create 7 two dimensional array in for
Take a look at the PHP online manual. The first example shows you how to create a multi dimensional array.
http://php.net/manual/en/function.array.php
<?php
$twoDimensionalArray = array (
"fruits" => array("a" => "orange", "b" => "banana", "c" => "apple"),
"numbers" => array(1, 2, 3, 4, 5, 6),
"holes" => array("first", 5 => "second", "third")
);
?>
To do what you want in a for loop, you can do so like this
// the following creates a 2d array. the first dimension contains 7 arrays of numbers 1 to 10
$firstDimension = array();
for ($i = 0; $i < 7; $i++) {
$firstDimension[] = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
}
Unlike some other langauges (such as standard C), arrays in PHP are "sparse" (i.e.: they only take up the space they need) so you can define a multi-dimensional array simply via:
$testArray = array();
(i.e.: You don't need to reserve the amount of space you're going to require.) However, more usefully, you can add values as follow:
$testArray = array();
$testArray[0][0] = "Hello";
$testArray[0][1] = "World";
...
That said, I'd recommend reading the PHP array manual page, as you might want to use named indexes, etc. and it has better examples.
Multi-dimentional arrays are like regular arrays but the value to some (or all) or their keys are arrays.
For example you can create a two dimentional array like this:
$arr = array();
$arr[1] = array(1 => 'one', 2 => 'two');
And you can use it like this:
echo $arr[1][1]; //which prints "one"
To create empty multidimensional array in PHP, you can do the following.
$arr_1 = array();
Yes. That's all. You can insert any type of data or array in it. There is no specific declaration of various arrays in PHP.
Now, suppose I want to insert data inside this multidimensional array $arr_1. I need to create an array of addresses. Each address item will have city, state and country.
You can do this as follows:
$arr_1[0] = array(
'city' => 'Gurgaon',
'state' => 'Haryana',
'country' => 'India'
);
$arr_1[1] = array(
'city' => 'Los Angeles',
'state' => 'California',
'country' => 'United States'
);
$arr_1[1] = array(
'city' => 'Melbourne',
'state' => 'Victoria',
'country' => 'Australia'
);
You can create as many arrays as you want in this way.
If you want to learn more about PHP arrays (Indexed, Associative, Multidimensional), visit PHP arrays explained with examples - Webolute Blog
<?php
$twoDimensionalArray = array (
"fruits" => array("a" => "orange", "b" => "banana", "c" => "apple"),
"numbers" => array(1, 2, 3, 4, 5, 6),
"holes" => array("first", 5 => "second", "third")
);
?>