I am trying to remove the last comma so that it will look like
1,2,3 instead of 1,2,3,
Here is what I have so far;
<?php
include_once 'header.php';
?>
<div id="content">
Lesson on arrays<br />
<?php
$nums = array(0, 1, 2, 3);
echo "My 1st array =";
foreach ($nums as $value) {
echo rtrim($value,",");
}
?>
</div>
<?php
include_once 'footer.php';
?>
Currently with the rtrim command in I am getting back
My 1st array =0123
Thanks for any help
Instead of for loop you can directly use implode function.
<?php
$nums = array(0, 1, 2, 3);
echo "My 1st array =";
echo implode(',',$nums);
?>
Edit : if you want foreach loop
<?php
$nums = array(0, 1, 2, 3);
echo "My 1st array =";
$str='';
foreach ($nums as $value) {
$str.= $value.",";
}
echo rtrim($str,',');
?>
Try this
$myStr = 'planes,trains,automobiles,';
$myStr = trim($myStr, ',');
Output
planes,trains,automobiles
Why to use foreach loop when you can do it without the loop, by using implode().
implode() function returns a string separated by a "seperater" from the elements of an array.
$nums = array(0, 1, 2, 3);
echo "My 1st array = ";
$str=implode(",",$nums);
echo $str;
This will give you the output as
My 1st array = 0,1,2,3
If you must use that setup then use the $key in the foreach to determine if there should be a comma or not.
$nums = array(0, 1, 2, 3);
echo "My 1st array =";
foreach ($nums as $key => $value) {
if($key !=0) echo ",";
echo $value;
}
https://3v4l.org/kKKg1
You have two ways you can do with
<?php
$string = "";
$nums = array(0, 1, 2, 3);
echo "My 1st array = ";
foreach ($nums as $value) {
$string .= $value.",";
}
print_r(rtrim($string,','));
?>
Or
<?php
$nums = array(0, 1, 2, 3);
$string_by_implode = implode(',',$nums);
echo "My 1st array = " . $string_by_implode;
?>
You can use more generic way like following, here comma is attached from second element onwards:
implode is the quickest way to achieve this as explained in previous answer but if you are using loop then use below code:
<?php
$nums = array(0, 1, 2, 3);
echo "My 1st array =";
$comma = '';
foreach ($nums as $key => $value) {
echo $comma . $value;
$comma = ',';
}
?>
Related
My array which is dynamic, formed as
$exam = explode(',',$row['exam']);
For example result is:
$exam = array("First-Term","Second-Term", "Third-Term");
We can get index and value as this
foreach (array_values($exam) as $i => $value) {
echo "$i: $valuen";
echo "//And its mark";
}
But, how can I break loop to each index. I have to fetch as follow
First-Term
//And its mark
Second-Term
// And its mark
Third-Term
// And its mark
But while using foreach loop, I am getting
First-Term
Second-Term
Third-Term
//And its mark
//And its mark
//And its mark
How to break loop to each index, after that we use same code in every index. I'm simply try to assign each marks to each term
$exam[0]{
//here is $value
//rest of the code, same code to every index
}
$exam[1]{
//here is $value
//rest of the code, same code to every index
}
$exam[2]{
//here is $value
//rest of the code, same code to every index
}
$exam[...]{
//
}
You should make two arrays for team and marks and then parse these two arrays in the same foreach loop like this
$team = array('a', 'b', 'c', 'd' );
$marks = array('1', '2', '3', '4' );
foreach(array_combine($team, $marks) as $t => $m) {
echo $t . "<br>" .$m . "<br><br>"; //$t for team and m for marks
echo "<br/>";
}
In this way you can parse your different data in a paralell way
From the looks of what you are doing, you are using two foreach loops with different output...
This one:
$exam = array("First-Term","Second-Term", "Third-Term");
foreach (array_values($exam) as $i => $value) {
echo "{$value}<br>";
echo "// And its mark<br><br>";
}
Will output this:
First-Term
//And its mark
Second-Term
// And its mark
Third-Term
// And its mark
While this loop:
$exam = array("First-Term","Second-Term", "Third-Term");
foreach (array_values($exam) as $i => $value) {
echo "{$value}<br>";
}
foreach (array_values($exam) as $i => $value) {
echo "// And its mark<br>";
}
Will output this:
First-Term
Second-Term
Third-Term
// And its mark
// And its mark
// And its mark
Will update this answer once I have more details.
Code tested: https://3v4l.org/RDvYN
I would build an array with everything in place and then start to display it:
$exam = array("First-Term","Second-Term", "Third-Term");
$marks = array(1, 2, 3);
$result = array();
foreach (array_values($exam) as $idx => $value) {
$result[] = array(
"exam" => $value,
"mark" => $marks[$idx]
);
}
foreach ($result as $value) {
echo $value['exam'] . "\n";
echo $value['mark'] . "\n\n";
}
<?php
$arr1 = preg_split("/[;]+/", $data);
foreach ($arr1 as $arr1 => $value) {
echo '<td>';
echo $value;
echo '</td>';
if (key($value)==6)
{
echo '</tr>';
echo '<tr>';
}
}
?>
This is code I am using but the key function is not returning anything.
I want to get return the position of $value and want to excecute some code if it is divisible by 6.
How can I get the position of $value in $arr1?
You must use a different variable than $arr1 to store the key.
Use this instead, where $key will be the key:
<?php
$arr1 = preg_split("/[;]+/", $data);
foreach ($arr1 as $key => $value) {
echo '<td>';
echo $value;
echo '</td>';
if ($key==6)
{
echo '</tr>';
echo '<tr>';
}
}
?>
You can following example to get position of particular $value in array.
<?php
$value = 'green';
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key_of_particular_value = array_search($value, array);
//After perform above operation $key_of_particular_value = 2
//Below statement will check whether key is divided by 6 or not
if(($key_of_particular_value % 6) == 0)
{
//perform your operation
}
?>
To know more please refer following link-
http://php.net/manual/en/function.array-search.php
You have used same variable $arr1 for key and original array, try using another variable to get key(index)
foreach ($arr1 as $key => $value) {
I am working with my code, that can convert a query string into array.
This is my query string:
key1=['PH','PHILIPPINES']&key2=['KR','KOREA']
And I want only to display the second row, something like this:
Philippines
Korea
In my code, it's working but it displays:
['PH','PHILIPPINES']
['KR','KOREA
Here is my code:
<?php
$get_string = "key1=['PH','PHILIPPINES']&key2=['KR','KOREA']";
parse_str($get_string, $get_array);
$colors = $get_array;
foreach ($colors as $key => $value) {
echo $value."<BR>";
}
?>
This is your code:
<?php
$get_string = "key1=['PH','PHILIPPINES']&key2=['KR','KOREA']";
parse_str($get_string, $get_array);
$colors = $get_array;
foreach ($colors as $key => $value) {
// remove first and last characters ( "[" and "]" )
$value = substr($value, 1, -1);
// explode
$value = explode(",", $value);
// remove "'"
$our_value = str_replace("'", "", trim($value[1]));
// show
echo ucfirst(strtolower($our_value))."<BR>";
}
?>
I think you need this.
just simple explode by comma , and preg_replace to get only alphabates.
$get_string = "key1=['PH','PHILIPPINES']&key2=['KR','KOREA']";
parse_str($get_string, $get_array);
$colors = $get_array;
foreach ($colors as $key => $value) {
$x = explode(",",$value);
$new_string = preg_replace("/[^A-Za-z0-9?!]/",'',$x[1]);
echo $new_string."<br>";
}
Output :
PHILIPPINES
KOREA
$var = array(
'PH'=>'PHILLIPINES',
'KR'=>'KOREA');
Else
$var= array(
array('KR'=>'KOREA'),
array('PH'=>'PHILLIPINES')
);
Then echo in
foreach loop.
This question already has answers here:
Retrieve array key passed on value PHP
(5 answers)
Closed 9 years ago.
I have an array like this:
$array = array('name'=>'Van Pham','age'=>'23','sex'=>'male');
How can I get key 'age' with value '23'?
you are looking for array_keys http://www.php.net/manual/en/function.array-keys.php
print_r(array_keys($array, "23")); // age
OR by HamZa DzCyberDeV
echo array_keys($array, "23")[0];
http://codepad.viper-7.com/bZErGT
try this
$my_arr = array('name'=>'Van Pham','age'=>'23','sex'=>'male');
echo get_array_by_value($my_arr, '23');
function get_array_by_value($my_arr = '', $arr_value = '') {
$new_arr = array_flip($my_arr);
if (isset($new_arr[$arr_value])) {
return $new_arr[$arr_value];
}
}
output
age
use array_search()
$key= array_search($value, $array);
example:
$array = array('name'=>'Van Pham','age'=>'23','sex'=>'male');
echo array_search("23", $array); //age
try this
<?php
$arr = array('name'=>'Van Pham','age'=>'23','sex'=>'male');
foreach ($arr as $key => $value) {
echo "Key: $key; Value: $value<br />\n";
}
?>
I think you want to find the keys, for values 23, do it like this:
$array = array('name'=>'Van Pham','age'=>'23','sex'=>'male');
while ($value = current($array)) {
if ($value == '23') {
echo key($array)."\n";
}
next($array);
}
Try with
foreach($array as $key => $value)
{
if($key == 'age' && $value == '23')
echo $key.'-'.$value;
}
<?php
$array = array('name'=>'Van Pham','age'=>'23','sex'=>'male');
echo array_keys($array, "23") .":". $array['age'];
?>
Output
age : 23
It can be done easily using array_search function.This Function Searches the array for a given value and returns the corresponding key if successful.
<?php
$array = array('name'=>'Van Pham','age'=>'23','sex'=>'male');
$key1 = array_search('23', $array);
echo '<p>Key 1='.$key1.'</p>';
$key2 = array_search('Van Pham', $array);
echo '<p>Key 2='.$key2.'</p>';
$key3 = array_search('male', $array);
echo '<p>Key 3='.$key3.'</p>';
$key4 = array_search('female', $array);
echo '<p>Key 4='.$key4.'</p>';
?>
Output:
Key 1=age
Key 2=name
Key 3=sex
Key 4=
DEMO
Perhaps I'm simply having trouble understanding how php handles arrays.
I'm trying to print out an array using a foreach loop. All I can seem to get out of it is the word "Array".
<?php
$someArray[]=array('1','2','3','4','5','6','7'); // size 7
foreach($someArray as $value){
echo $value;
?>
<br />
<?php
}
?>
This prints out this:
Array
I'm having trouble understanding why this would be the case. If I define an array up front like above, it'll print "Array". It almost seems like I have to manually define everything... which means I must be doing something wrong.
This works:
<?php
$someArray[0] = '1';
$someArray[1] = '2';
$someArray[2] = '3';
$someArray[3] = '4';
$someArray[4] = '5';
$someArray[5] = '6';
$someArray[6] = '7';
for($i=0; $i<7; $i++){
echo $someArray[$i]."<br />";
}
?>
Why won't the foreach work?
here's a link to see it in action >> http://phpclass.hylianux.com/test.php
You haven't declared the array properly.
You have to remove the square brackets: [].
<?php
$someArray=array('1','2','3','4','5','6','7'); // size 7
foreach($someArray as $value){
echo $value;
?> <br />
<?php
}
?>
Try:
<?php
$someArray = array('1','2','3','4','5','6','7'); // size 7
foreach($someArray as $value){
echo $value . "<br />\n";
}
?>
Or:
<?php
$someArray = array(
0 => '1',
'a' => '2',
2 => '3'
);
foreach($someArray as $key => $val){
echo "Key: $key, Value: $val<br/>\n";
}
?>
actually, you're adding an array into another array.
$someArray[]=array('1','2','3','4','5','6','7');
the right way would be
$someArray=array('1','2','3','4','5','6','7');