How to get a index of an array element - php

I need to get the index of the array element, in my case $ch is an array element, I need the index value (for e.g.:overview=array[0], $arval = 0), so i could print the $tabs[$arval+1].
<?php
$tab ='overview,gallery,video,songs$value1$value2$value3$value4';
$tabs = explode('$',$tab);
$tabname = explode(',',$tabs[0]);
echo '<div id="tab" style="float:left;width:100%;height:30px;background:#333">';
foreach($tabname as $i)
{
echo '<a id="'.$i.'" style="color:#fff;padding:2px 10px;" href="?tab='.$i.'" >'.$i.'</a>';
}
echo '</div>';
if(isset($_GET['tab']))
{
$ch=$_GET['tab'];
foreach($tabname as $i){
if ($ch == $i)
// get the array index of the current element $arval
// echo $tabs[$arval+1]
} } ?>
How can I accomplish it?

foreach($tabname as $index => $i){
^^^^^^^^^

Maybe this could work for you:
if(isset($_GET['tab']))
{
$ch=$_GET['tab'];
if($key = array_search($ch, $tabname, true))
// get the array index of the current element $arval
echo $tabs[$key];
}
}

In your foreach you need to do this:
foreach($tabname as $index => $value){
// $index is the index
// $value is the value
if ($ch == $i)
// get the array index of the current element $arval
// echo $tabs[$arval+1]
}

Related

Filter JSON array with objects inside in PHP

I have a particular JSON file that looks like this:
[
{
"objID":"kc6BvvNlVW",
"string":"bill",
"createdOn":"2018-09-18T01:51:02",
"updatedOn":"2018-09-18T01:51:02",
"number":1,
"boolean":true,
"array":["item1","item2"],
"pointer":{"type":"__pointer","objID":"hYtr54Ds","className":"Users"}
},
{
"objID":"sS1IwFPPWh",
"string":"tom",
"createdOn":"2018-09-18T01:59:40",
"updatedOn":"2018-09-18T01:59:40",
"number":12.3,
"boolean":false,
"array":["item1","item2"],
"pointer":{"type":"__pointer","objID":"tRe4Fda5","className":"Users"}
}
]
1. I need to first check if the "pointer" object has "__pointer" inside the type key and show only the objID value in an HTML table, like this:
"tRe4Fda5"
Right now, this is how my table looks like:
And here's my foreach PHP code (into a table row):
foreach($jsonObjs as $i=>$obj) {
$row_id = $i;
echo '<tr>';
foreach($obj as $key => $value){
// $value is an Array:
if (is_array($value)) {
echo '<td>';
foreach($value as $k=>$v){
// $v is a Pointer
if ($v === '__pointer') {
echo json_encode($v); // <-- WHAT SHOULD I DO HERE ?
// $v is an Array:
} else {
echo json_encode($v);
}
}
echo '</td>';
// $value is a Number:
} else if (is_numeric($value)){
echo '<td>'.(float)$value.'</td>';
// $value is a String:
} else { echo '<td>'.$value.'</td>'; }
}
As you can see in the pointer column, the string I get is:
"__pointer""hYtr54Ds""Users"
with no commas as separators, so this is the line of code I need to edit:
echo json_encode($v); // <-- WHAT SHOULD I DO HERE ?
I've tried with echo json_encode($v[$k]['__ponter']);, but no positive results.
So my final first question is: how can I get each VALUE of the "pointer" array?
2. Also, the second row of the boolean column shows noting since its value is false, shouldn't it show 0, since the first row shows 1 (true)?
You can look into the object during the second loop to see if it has a property called type and if that property is set to __pointer.
foreach($jsonObjs as $i=>$obj) {
$row_id = $i;
foreach($obj as $key => $value){
// see if $value has a type property that is set to pointer
if (isset($value['type']) && $value['type'] == "__pointer") {
// $value is the pointer object. Do with it what you will
echo "<td>" . $value['objID'] . "</td>";
}
// more code
}
}
instead of
foreach($value as $k=>$v){
// $v is a Pointer
use
foreach($value as $k)
{
//then check for pointer
if($k->type === '__pointer')
{
echo json_decode($k); //here you will get proper key and value
}
}

PHP displaying arrays having duplicate with color=red [duplicate]

This question already has answers here:
PHP highlight duplicate values in array [duplicate]
(2 answers)
Closed last month.
I have a array that i want to check if has duplicates using PHP
$i=array('One','Two','Two','Three','Four','Five','Five','Six');
I was able to achieve it by using below function
function array_not_unique($input) {
$duplicates=array();
$processed=array();
foreach($input as $i) {
if(in_array($i,$processed)) {
$duplicates[]=$i;
} else {
$processed[]=$i;
}
}
return $duplicates;
}
I got below output
Array ( [0] => Two [1] => Five )
Now how can i display the previous arrays and mark values with duplicates referencing the array_not_unique function return values to a HTML table.
My goal is to display the duplicated values with red font color.
Try this piece of code... simplest and shortest :)
$i=array('One','Two','Two','Three','Four','Five','Five','Six');
$arrayValueCounts = array_count_values($i);
foreach($i as $value){
if($arrayValueCounts[$value]>1){
echo '<span style="color:red">'.$value.'</span>';
}
else{
echo '<span>'.$value.'</span>';
}
}
Here is optimized way that will print exact expected output.
<?php
$i=array('One','Two','Two','Three','Four','Five','Five','Six');
$dups = array_count_values($i);
print_r($dups);
foreach($i as $v)
{
$colorStyle = ($dups[$v] > 1) ? 'style="color:red"' : '';
echo "<span $colorStyle>$v</span>";
}
?>
Try this,
function array_not_unique($input) {
$duplicates=array();
$processed=array();
foreach($input as $key => $i) {
if(in_array($i,$processed)) {
$duplicates[$key]=$i; // fetching only duplicates here and its key and value
}
}
return $duplicates;
}
foreach($processed as $k => $V){
if(!empty($duplicates[$k])){ // if duplicate found then red
echo '<span style="color:red">'.$duplicates[$k].'</span>';
}else{
echo '<span>'.$duplicates[$k].'</span>'; // normal string
}
}
Like this :
PHP
function array_duplicate_css($input) {
$output = $processed = array();
foreach($input as $key => $i) {
$output[$key]['value'] = $i;
if(in_array($i, $processed)) {
$output[$key]['class'] = 'duplicate';
} else {
$output[$key]['class'] = '';
$processed[] = $i;
}
}
return $output;
}
foreach(array_duplicate_css($input) as $row) {
echo '<tr><td class="' . $row['class'] . '">' . $row['value'] . '</td></tr>';
}
CSS
.duplicate {
color: #ff0000;
}
Simple use array_count_values.
$array=array('One','Two','Two','Three','Four','Five','Five','Six');
$new_array= array_count_values($array);
foreach($new_array as $key=>$val){
if($val>1){
for($j=0;$j<$val;$j++){
echo "<span style='color:red'>".$key."</span>";
}
}else{
echo "<span>".$key."</span>";
}
}
It can be done in several ways. This is just a one method. Step one maintain 2 arrays. Then store the duplicated indexes in one array. When you iterating use a if condition to check whether the index is available in the "duplicated indexes" array. If so add the neccessary css.

How to get position of a value in a php array

<?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) {

PHP - replace values in sub array

I have two arrays $pq and $rs. please see them below:
$pq = array ('page-0'=>array ('line-0'=>array('item-0'=>array('name'=>"item-00",'value'=>"123"),
'item-1'=>array('name'=>"item-01",'value'=>"456")
),
'line-1'=>array('item-0'=>array('name'=>"item-10",'value'=>"789"),
'item-1'=>array('name'=>"item-11",'value'=>"012")
)),
'page-1'=>array ('line-0'=>array('item-0'=>array('name'=>"item-100",'value'=>"345"),
'item-1'=>array('name'=>"item-101",'value'=>"678")
),
'line-1'=>array('item-0'=>array('name'=>"item-110",'value'=>"901"),
'item-1'=>array('name'=>"item-111",'value'=>"234")
),
'line-2'=>array('item-0'=>array('name'=>"item-210",'value'=>"567"),
'item-1'=>array('name'=>"item-211",'value'=>"890")
))
);
$rs = array ('1'=>array('name'=>'item-00', 'value'=>"abc"),
'2'=>array('name'=>'item-01', 'value'=>"def"),
'3'=>array('name'=>'item-10', 'value'=>"ghi"),
'4'=>array('name'=>'item-11', 'value'=>"jkl"),
'5'=>array('name'=>'item-100', 'value'=>"mno"),
'6'=>array('name'=>'item-101', 'value'=>"pqr"),
'7'=>array('name'=>'item-110', 'value'=>"stu"),
'8'=>array('name'=>'item-111', 'value'=>"vwx")
);
What I am trying to do is to replace the values in $pq for items with the values from $rs.
for example item-01 in $pa to be replaced with abc from $rs.
What I tried is this:
foreach($rs as &$rs1) {
echo "first count :".$firstCount."<br>";
foreach($pq as $pages) {
foreach($pages as $lines) {
foreach($lines as &$item) {
if ($item['name'] == $rs1['name']) { echo "matching </p>";
$item['value']=$rs1['value'];
echo '<pre>';
print_r($item);
echo '</pre>';
echo "<hr>";
}
}
}
}
}
When I print the values of $item from $pq, it prints the values from $rs, but when I print the whole array $pq, the values seem to be unchanged.
Can anyone please help me find out what I am missing ?
You're correctly looping through the items in each line by reference, but you're not doing it for the lines or pages themselves. So you're updating the value of an item in a copy of the line, instead of the line itself. It should be:
foreach($rs as $rs1) {
echo "first count :".$firstCount."<br>";
foreach($pq as &$pages) {
foreach($pages as &$lines) {
foreach($lines as &$item) {
if ($item['name'] == $rs1['name']) { echo "matching </p>";
$item['value']=$rs1['value'];
echo '<pre>';
print_r($item);
echo '</pre>';
echo "<hr>";
}
}
}
}
}
Note that the & in front of &$lines and &$pages. Note also that $rs1 doesn't need to be passed by reference, since you aren't changing anything in that array.
You’ve assigned $item by reference but haven’t done the same for $pages and $lines. There will be no effect on the actual values of $pq unless you assign $pages by reference; similarly, the actual values of $pages will remain unchanged unless you assign $lines by reference. Therefore, in order to achieve what you want, change foreach($pq as $pages) to foreach($pq as &$pages) and foreach($pages as $lines) to foreach($pages as &$lines).
You can build a search array first so that you can match items easier:
$search = array_reduce($rs, function(&$prev, $current) {
$prev[$current['name']] = $current;
return $prev;
}, []);
This creates another array with the item name as the key. Then, you iterate over each item in $pq and modify the leaves where necessary:
foreach ($pq as &$page_data) {
foreach ($page_data as &$line_data) {
foreach ($line_data as &$item_data) {
if (isset($search[$item_data['name']])) {
$item_data = $search[$item_data['name']];
}
}
}
}
Make sure to use references at each level of iteration.

How can I get the current array index in a foreach loop?

How do I get the current index in a foreach loop?
foreach ($arr as $key => $val)
{
// How do I get the index?
// How do I get the first element in an associative array?
}
In your sample code, it would just be $key.
If you want to know, for example, if this is the first, second, or ith iteration of the loop, this is your only option:
$i = -1;
foreach($arr as $val) {
$i++;
//$i is now the index. if $i == 0, then this is the first element.
...
}
Of course, this doesn't mean that $val == $arr[$i] because the array could be an associative array.
This is the most exhaustive answer so far and gets rid of the need for a $i variable floating around. It is a combo of Kip and Gnarf's answers.
$array = array( 'cat' => 'meow', 'dog' => 'woof', 'cow' => 'moo', 'computer' => 'beep' );
foreach( array_keys( $array ) as $index=>$key ) {
// display the current index + key + value
echo $index . ':' . $key . $array[$key];
// first index
if ( $index == 0 ) {
echo ' -- This is the first element in the associative array';
}
// last index
if ( $index == count( $array ) - 1 ) {
echo ' -- This is the last element in the associative array';
}
echo '<br>';
}
Hope it helps someone.
foreach($array as $key=>$value) {
// do stuff
}
$key is the index of each $array element
$i = 0;
foreach ($arr as $key => $val) {
if ($i === 0) {
// first index
}
// current index is $i
$i++;
}
The current index is the value of $key. And for the other question, you can also use:
current($arr)
to get the first element of any array, assuming that you aren't using the next(), prev() or other functions to change the internal pointer of the array.
You can get the index value with this
foreach ($arr as $key => $val)
{
$key = (int) $key;
//With the variable $key you can get access to the current array index
//You can use $val[$key] to
}
$key is the index for the current array element, and $val is the value of that array element.
The first element has an index of 0. Therefore, to access it, use $arr[0]
To get the first element of the array, use this
$firstFound = false;
foreach($arr as $key=>$val)
{
if (!$firstFound)
$first = $val;
else
$firstFound = true;
// do whatever you want here
}
// now ($first) has the value of the first element in the array
You could get the first element in the array_keys() function as well. Or array_search() the keys for the "index" of a key. If you are inside a foreach loop, the simple incrementing counter (suggested by kip or cletus) is probably your most efficient method though.
<?php
$array = array('test', '1', '2');
$keys = array_keys($array);
var_dump($keys[0]); // int(0)
$array = array('test'=>'something', 'test2'=>'something else');
$keys = array_keys($array);
var_dump(array_search("test2", $keys)); // int(1)
var_dump(array_search("test3", $keys)); // bool(false)
well since this is the first google hit for this problem:
function mb_tell(&$msg) {
if(count($msg) == 0) {
return 0;
}
//prev($msg);
$kv = each($msg);
if(!prev($msg)) {
end($msg);
print_r($kv);
return ($kv[0]+1);
}
print_r($kv);
return ($kv[0]);
}
based on #fabien-snauwaert's answer but simplified if you do not need the original key
$array = array( 'cat' => 'meow', 'dog' => 'woof', 'cow' => 'moo', 'computer' => 'beep' );
foreach( array_values( $array ) as $index=>$value ) {
// display the current index + value
echo $index . ':' . $value;
// first index
if ( $index == 0 ) {
echo ' -- This is the first element in the associative array';
}
// last index
if ( $index == count( $array ) - 1 ) {
echo ' -- This is the last element in the associative array';
}
echo '<br>';
}

Categories